我想在我的查询中集成Textbox。经过几个小时的互联网搜索,我发现了以下代码。有没有更好的解决方案?

时间:2014-08-07 02:23:18

标签: sql sql-server vb.net parameterized

'代码

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()

1 个答案:

答案 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