我无法解决此问题“FROM Clause中的语法错误”
这是我的代码:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
myConnetion = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\iponz18\Documents\Visual Studio 2012\Projects\CanteenBillingSystem\CanteenBillingSystem\CanteenBillingSystem.accdb")
Dim table As String = "SELECT UserID FROM User WHERE UserID = " + TextBox1.Text + ";"
da = New OleDbDataAdapter(table, myConnetion)
ds = New DataSet
da.Fill(ds, "User")
If (ds.Tables("User").Rows.Count > 0) Then
Form2.Show()
Me.Close()
End If
End Sub
错误在这一行:
da.Fill(ds,“用户”)
请帮帮我......
答案 0 :(得分:3)
User
是MS-Access中的保留关键字。你需要把它放在方括号
Dim table As String = "SELECT UserID FROM [User] WHERE UserID = ...
说,你的查询还有其他问题。这是一个更好的方法:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim table As String = "SELECT UserID FROM User WHERE UserID = @uid"
Using conn = New OleDbConnection(.....)
Using da = New OleDbDataAdapter(table, conn )
da.SelectCommand.Parameters.Add("@uid", OleDbType.VarWChar).Value = textBox1.Text
ds = New DataSet
da.Fill(ds, "User")
If (ds.Tables("User").Rows.Count > 0) Then
Form2.Show()
End If
End Using
End Using
End Sub
我已将字符串连接的查询文本更改为参数化查询。这种方法更安全,因为它避免了Sql Injection并且无需正确地转义字符串。
我认为另一个非常重要的建议是不惜一切代价避免全局变量来保持连接或适配器等对象。当出现意外情况并且您的连接处于不可预测的状态时,这会给您带来很多麻烦。
最后,如果您只需要检查表中是否有UserID,则无需构建OleDbDataAdapter,DataSet并填充它。您可以使用OleDbCommand的ExecuteScalar方法
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim table As String = "SELECT UserID FROM User WHERE UserID = @uid"
Using conn = New OleDbConnection(.....)
Using cmd = New OleDbCommand(table, conn )
cmd.Parameters.Add("@uid", OleDbType.VarWChar).Value = textBox1.Text
conn.Open()
Dim result = cmd.ExecuteScalar()
if result IsNot Nothing then
Form2.Show()
End If
End Using
End Using
End Sub