【发布时间】:2016-11-08 03:14:11
【问题描述】:
我想使用 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 = 长文本
office = 长文本
名称 = 长文本
任何帮助将不胜感激,谢谢,
【问题讨论】:
-
我认为您的查询应该是
select count(*) from personnel where pcode = @pcode,因为您似乎想检查您的命令是否返回了行 -
尝试使用计数,但在 intReturn = sqlcmd.ExecuteScalar 声明时出现新错误,
标签: mysql vb.net validation