gpt4 book ai didi

mysql - 在调用 Read() INSERT 之前访问字段的尝试无效

转载 作者:行者123 更新时间:2023-11-29 01:04:06 24 4
gpt4 key购买 nike

我正在尝试使用这段代码来检查系统是否已经存在具有该值的字段

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。如果记录存在,则 data.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)"

关于mysql - 在调用 Read() INSERT 之前访问字段的尝试无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13043234/

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