Use*_*341 1 mysql vb.net validation
我想使用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
Run Code Online (Sandbox Code Playgroud)
结束子
我在搜索答案时发现了这一点,但是当我试图运行它时,它不会读取插入命令,而是直接进入msbox"人员ID已经存在",即使没有相同的人员ID.
有人可以检查为什么它不读取插入,请
我的数据库表值:
pcode =主键
lname = longtext
fname = longtext
office = longtext
指定= longtext
任何帮助将不胜感激,谢谢,
很抱歉,这是错误的做法.
数据库具有内置系统以防止数据被复制.这是通过主键或唯一键约束.在您的情况下,您已经创建了一个主键.因此,您无需进行该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
Run Code Online (Sandbox Code Playgroud)
另请参阅MySQL手册页PRIMARY KEY和UNIQUE Index Constraints