Dim conStr As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\databaseVB\bakery.accdb"
Dim conn As New OleDbConnection(conStr)
Dim cmd As New OleDbCommand
Dim reader As OleDbDataReader
Dim Item(5) As String
Dim key = TextBox1.Text
conn.Open()
cmd.Connection = conn
1>>>>> 'cmd.CommandText = "SELECT * FROM Member WHERE number = 3"
2>>>>> cmd.CommandText = "SELECT * FROM Member WHERE number = '" & key & "'"
MessageBox.Show(cmd.CommandText)
reader = cmd.ExecuteReader()
While reader.Read
Item(0) = reader("Number").ToString
Item(1) = reader("FirstName").ToString
Item(2) = reader("LastName").ToString
Item(3) = reader("User").ToString
Item(4) = reader("Pass").ToString
End While
MessageBox.Show(Item(1).ToString)
conn.Close()
来自1>>>我可以在数据库中阅读Item 从2>>>我看不懂物品
答案 0 :(得分:0)
尝试使用参数化查询字符串:
cmd.CommandText = "SELECT * FROM Member WHERE number = @Number"
在此之后添加您的参数。
//cmd.Parameters.Add("@Number", SqlDbType.Int).Value = 3;
//It is better to use .TryParse(), incase your users write non numerical values in the Textbox
cmd.Parameters.Add("@Number", SqlDbType.Int).Value = (int)TextBox1.Text;
此外,您还需要观察数据类型。 3
的类型为int
,但TextBox1.Text
的类型为string
。您需要将字符串解析为int才能使其正常工作。
这应该可以解决问题并防止丑陋的语法杂乱,同时混合字符串和变量;并防止您受到SQL注入攻击。