我试图用这个代码检查系统是否已经存在一个具有这个值的字段
Dim adap As New MySqlDataAdapter
Dim sqlquery = "SELECT * FROM client WHERE code ='"+ TxtCode.Text +"'"
Dim comand As New MySqlCommand()
comand.Connection = con
comand.CommandText = sqlquery
adap.SelectCommand = comand
Dim data As MySqlDataReader
data = comando2.ExecuteReader()
leitor.Read()
If (data(3).ToString) = code Then
MsgBox("already exists", MsgBoxStyle.Information)
TxtCode.ResetText()
TxtCode.Focus()
Else
Console.WriteLine(insert("INSERT INTO client (name, tel, code) VALUES ('" & name & "', '" & tel & "')"))
con.Close()
End If
最佳答案
您调用了leitor.Read()
,但在代码中没有调用data.Read()
另外,由于您的查询是SELECT * FROM client WHERE code = '1234'
,因此无需检查data(3) == code
。如果存在记录,则数据.Read()将为真。
If data.Read() Then
MsgBox("already exists", MsgBoxStyle.Information)
TxtCode.ResetText()
TxtCode.Focus()
Else
Console.WriteLine(insert("INSERT INTO client (name, tel, code) VALUES ('" & name & "', '" & tel & "')"))
con.Close()
End If
使用参数而不是连接也是一个好的实践
Dim sqlquery = "SELECT * FROM client WHERE code = @code"
...
command.Parameters("@code", code); //this is safer
还有你的插页
"INSERT INTO client (name, tel, code) VALUES (@name, @tel)"