gpt4 book ai didi

mysql - 防止重复输入数据库

转载 作者:行者123 更新时间:2023-11-30 22:09:33 24 4
gpt4 key购买 nike

我想使用 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

结束子

我在搜索答案时发现了这个,但是当我尝试运行它时,它不会读取插入命令,而是直接转到 msbox“人员 ID 已经存在”,即使没有相同的人员 ID。

有人能检查一下为什么它没有阅读插入内容吗,

我的数据库表值:

pcode = 主键

lname = 长文本

fname = 长文本

办公室 = 长文本

名称 = 长文本

任何帮助将不胜感激,谢谢,

最佳答案

很抱歉,这是错误的做法。

数据库有一个内置系统来防止数据被复制。那是通过主键或唯一键约束。在您的情况下,您已经创建了一个主键。因此,您完全没有必要执行该 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 and UNIQUE Index Constraints

关于mysql - 防止重复输入数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40541136/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com