我想防止使用vb.net和MySQL作为数据库的清单表单中出现重复条目,这是我的代码:
Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click Dim myCommand As New MySqlCommand Dim conn As MySqlConnection Dim i As String conn = New MySqlConnection conn.ConnectionString = "server = localhost;username= root;password= a;database= secret" Try conn.Open() Catch mali As MySqlException MsgBox("connot establish connection") End Try Dim intReturn As Integer Dim strSql As String = " select * from personnel where pcode = @pcode" Dim sqlcmd As New MySqlCommand(strSql, conn) With sqlcmd.Parameters .AddWithValue("@pcode", CType(pcode.Text, String)) End With intReturn = sqlcmd.ExecuteScalar If (intReturn > 0) Then cmd = New MySqlCommand("Insert into personnel values('" & pcode.Text & "','" & lname.Text & "','" & fname.Text & "','" & office.Text & "','" & designation.Text & "')") i = cmd.ExecuteNonQuery If pcode.Text <> "" Then ElseIf i > 0 Then MsgBox("Save Successfully!", MessageBoxIcon.Information, "Success") mrClean() ListView1.Tag = "" Call objLocker(False) Call LVWloader() Call calldaw() Else MsgBox("Save Failed!", MessageBoxIcon.Error, "Error!") End If Else MsgBox("Personnel ID Already Exist!", MessageBoxIcon.Error, "Error!") End If
结束子
我在搜索答案时发现了这个问题,但是当我尝试运行它时,它没有读取插入命令,而是即使没有相同的人员ID也会直接转到msbox“人员ID已经存在”。
有人可以检查为什么不阅读插入内容,
我的数据库表值:
pcode =主键
lname =长文本
fname =长文本
办公室=长文本
名称=长文本
任何帮助将不胜感激,谢谢,
抱歉地说这是错误的方法。
数据库具有内置系统,可防止数据重复。这是通过主键或唯一键约束实现的。对于您的情况,您已经创建了一个主键。因此,绝对不需要您执行该SELECT COUNT(*)查询。
SELECT COUNT(*)
而是直接将其插入表中,并在pcode已经存在时捕获完整性错误。
Try cmd = New MySqlCommand("Insert into personnel values('" & pcode.Text & "','" & lname.Text & "','" & fname.Text & "','" & office.Text & "','" & designation.Text & "')") i = cmd.ExecuteNonQuery If pcode.Text <> "" Then ElseIf i > 0 Then MsgBox("Save Successfully!", MessageBoxIcon.Information, "Success") mrClean() ListView1.Tag = "" Call objLocker(False) Call LVWloader() Call calldaw() Else MsgBox("Save Failed!", MessageBoxIcon.Error, "Error!") End If Catch ex As MySqlException MsgBox("Personnel ID Already Exist!", MessageBoxIcon.Error, "Error!") End Try
另请参见MySQL手册页PRIMARY KEY和UNIQUE索引约束