0

只是为了让你知道这是我在这个网站上发布的第一个问题,所以如果我错过了任何事情,请告诉我。我遇到的问题是,当程序运行时,我收到以下错误消息

FROM 子句中的语法错误

代码在这里

    Dim dbProvider As String
    Dim dbSource As String
    Dim con As New OleDb.OleDbConnection
    Dim ds As New DataSet
    Dim MaxRows As Integer
    Dim sql As String
    Dim TableName As String
    Dim TableCreate As New OleDb.OleDbCommand("CREATE TABLE [" & TableName & "](" & "ID INTEGER NOT NULL," & ")", con)
    Dim da As New OleDb.OleDbDataAdapter("SELECT * FROM  [" & TableName & "]", con)
    Dim cb As New OleDb.OleDbCommandBuilder(da)

    TableName = TbTableName.Text

    dbProvider = "PROVIDER=Microsoft.Jet.OLEDB.4.0;"
    dbSource = "Data Source = E:\A2 Computing\Project\PasswordDatabase.mdb"

    con.ConnectionString = dbProvider & dbSource

    con.Open()

    da.Fill(ds, "NewTable")

    MaxRows = ds.Tables("NewTable").Rows.Count

我遇到的问题是在这条线上

    da.Fill(ds, "NewTable")

我不确定我错过了什么,当我声明 tablecreate 或 da 时,我猜测它与括号有关?=S 任何帮助将不胜感激。=)

4

1 回答 1

1

您需要在使用TableName 之前分配一些东西,而不是之后。您当前的 SQL 是SELECT * FROM [],这就是您在此处遇到语法错误的原因。

更改代码的顺序:

Dim TableName As String
TableName = TbTableName.Text

Dim TableCreate As New OleDb.OleDbCommand("CREATE TABLE [" & TableName & "](" & _
   "ID INTEGER NOT NULL" & ")", con)
Dim da As New OleDb.OleDbDataAdapter("SELECT * FROM  [" & TableName & "]", con)
Dim cb As New OleDb.OleDbCommandBuilder(da)

您还需要执行该TableCreate语句。IIRC,你曾经ExecuteNonQuery这样做过。

TableCreate.ExecuteNonQuery;

顺便说一句,您的表创建 SQL 可以简化:

' Remove unnecessary concatenation for column definition, as it's always
' the same
Dim TableCreate As New OleDb.OleDbCommand("CREATE TABLE [" & TableName & _
  "](ID INTEGER NOT NULL)", con)

您实际上在哪里连接到数据库?OleDBConnection我在您的代码中没有看到任何地方?

这是OleDBCommand.ExecuteNonScalar的 MSDN 文档中的完整示例:

Private Sub CreateOleDbCommand( _
      ByVal queryString As String, ByVal connectionString As String)
  Using connection As New OleDbConnection(connectionString)
    connection.Open()
    Dim command As New OleDbCommand(queryString, connection)
    command.ExecuteNonQuery()
  End Using
End Sub

另外,您知道这样做CREATE TABLE会创建一个新的空表,因此您的SELECT * FROM它不会返回任何内容,只返回NULL一行,因为您没有插入任何数据?

于 2012-05-07T22:47:44.873 回答