我的编码中出现此错误,请您告诉我可能出错的地方?以及如何纠正它
已经有一个与此Connection关联的打开DataReader,必须先关闭它。 在这个子我在if部分和我正在插入数据的else部分检索数据。如果条件不满意。所以在其他部分我得到了上述错误
代码是:
Dim con As MySql.Data.MySqlClient.MySqlConnection = New MySqlClient.MySqlConnection("server=localhost;user=root;database=zzz;port=3306;password;")
con.Open()
Dim cmd As MySqlClient.MySqlCommand
Dim dr As MySqlClient.MySqlDataReader
cmd = con.CreateCommand()
cmd.CommandText = "select sino FROM customers WHERE sino =('" + serialno.Text + "')"
cmd.ExecuteNonQuery()
dr = cmd.ExecuteReader()
If dr.HasRows = True Then
MsgBox("number already exists")
dr.Close()
ElseIf dr.HasRows = False Then
Dim sqlc As String
sqlc = "insert into customers values('" + serialno.Text + "','" + custname.Text + "','" + address.Text + "','" + phno.Text + "','" + eid.Text + "','" + event_type.Text + " ')"
Dim command As MySqlClient.MySqlCommand = New MySqlClient.MySqlCommand(sqlc, con)
command.ExecuteNonQuery()
MessageBox.Show(sqlc)
con.Close()
End If
答案 0 :(得分:2)
DataReader只能与一个打开的连接相关联。完成DataReader后,请确保在重新使用之前关闭()它。
来自MSDN: http://msdn.microsoft.com/en-us/library/haa3afyz(v=vs.80).aspx
答案 1 :(得分:0)
1)删除cmd.ExecuteNonQuery()。紧接着的ExecuteReader是您需要的唯一执行。 2)您必须为插入命令使用不同的连接对象或关闭以前的阅读器。在循环连接到它的阅读器时,不能重复使用相同的连接对象。所以试试这个:
Dim con As MySql.Data.MySqlClient.MySqlConnection = New MySqlClient.MySqlConnection("server=localhost;user=root;database=zzz;port=3306;password;")
con.Open()
Dim cmd As MySqlClient.MySqlCommand
Dim dr As MySqlClient.MySqlDataReader
cmd = con.CreateCommand()
cmd.CommandText = "select sino FROM customers WHERE sino =('" + serialno.Text + "')"
dr = cmd.ExecuteReader()
If dr.Read = False Then
'we have no existing record
dr.Close() 'close reader first
Dim sqlc As String
sqlc = "insert into customers values('" + serialno.Text + "','" + custname.Text + "','" + address.Text + "','" + phno.Text + "','" + eid.Text + "','" + event_type.Text + " ')"
Dim command As MySqlClient.MySqlCommand = New MySqlClient.MySqlCommand(sqlc, con)
command.ExecuteNonQuery()
MessageBox.Show(sqlc)
con.Close()
Else
MsgBox("number already exists")
dr.Close()
End If
con.Close() 'close connection before leaving