无法用数据填充OleDbDataAdapter

时间:2011-03-12 13:30:34

标签: database vb.net ms-access oledbexception

我无法填写OleDbDataAdapter

中的数据

我收到OleDbException,其中包含以下消息 Syntax error in FROM clause.

此行adapter.Fill(dataset, "User")

这是代码

Imports System.Data.OleDb

Public Class Form1

Public connection As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\MyDatabase.mdb;Persist Security Info=False")

Private Sub button_display_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles button_display.Click
    connection.Close()
    connection.Open()
    Dim adapter As New OleDbDataAdapter
    adapter.SelectCommand = New OleDbCommand
    adapter.SelectCommand.Connection = connection
    adapter.SelectCommand.CommandText = "select * from user;"

    Dim dataset As New DataSet
    adapter.Fill(dataset, "User")
    connection.Close()
    Dim datarow = dataset.Tables("User").Rows(0)
    Dim fname, lname As String
    fname = datarow(0)
    lname = datarow(1)
    txtfirstname.Text = fname
    txtlastname.Text = lname

End Sub
End Class

我试过替换

    Dim adapter As New OleDbDataAdapter
    adapter.SelectCommand = New OleDbCommand
    adapter.SelectCommand.Connection = connection
    adapter.SelectCommand.CommandText = "select * from user;"

    Dim dataset As New DataSet
    adapter.Fill(dataset, "User")

    Dim adapter As New OleDbDataAdapter("select * from user;", connection)
    Dim dataset As New DataSet
    adapter.Fill(dataset, "User")

我也尝试了

    Dim adapter As New OleDbDataAdapter
    adapter.SelectCommand = New OleDbCommand("select * from user;", connection)
    Dim dataset As New DataSet
    adapter.Fill(dataset)

但我得到了相同的异常Syntax error in FROM clause

2 个答案:

答案 0 :(得分:6)

用户是保留字。它应该这样写:

"select * from [user];"

注意方括号。最好通过重命名表来完全避免使用保留字。

答案 1 :(得分:0)

我不确定adapter.SelectCommand =新的OleDbCommand是正确的(我没有做太多的VB所以我可能是错的)无论如何你为什么要关闭连接然后打开然后不关闭它?移动你的接近结束。

尝试这样的事情:

Dim conn As New OleDbConnection(connection)
Dim adapter As New OleDbDataAdapter()
conn.Open()
adapter.SelectCommand = new OleDbCommand("Select * From User", conn)
DataSet dataset As New DataSet
adapter.Fill(dataset)
conn.Close()

'其余代码