'代码
Dim conn as SqlConnection = new SqlConnection("SERVER=LOGIC\SERVERDB;DATABASE=sample;User=sa;Pwd=codename")
conn.Open()
Dim userId as String = txtUserId.Text
Dim sql as String = "SELECT name, password FROM users WHERE id=@userid"
Dim cmd as SqlCommand = new SqlCommand()
cmd.Connection = conn
cmd.CommandType = CommandType.Text
cmd.CommendText = sql
cmd.Parameters.AddWithValue("userid", userId);
Dim dr as SqlDataReader = cmd.ExecuteReader()
答案 0 :(得分:0)
如果您愿意采纳,只需稍作修改即可:
SqlConnection
实施IDisposable。尝试用Using
块包裹它,here就是原因。
不确定您以后是否在某处使用您的姓名和密码。如果在后面的部分中没有使用它,为什么不直接发送为param和SELECT Count
,然后ExecuteScalar?
如果userId
仅使用一次,我会减少一行代码而不声明变量
Using conn As New SqlConnection("SERVER=LOGIC\SERVERDB;DATABASE=sample;User=sa;Pwd=codename")
conn.Open()
Dim sql As String = "SELECT name, password FROM users WHERE id=@userid"
Dim cmd As New SqlCommand
cmd.Connection = conn
cmd.CommandType = CommandType.Text
cmd.CommandText = sql
cmd.Parameters.AddWithValue("@userid", txtUserId.Text)
Dim dr As SqlDataReader = cmd.ExecuteReader()
End Using