FROM子句vb.net中的语法错误

时间:2012-05-07 22:37:17

标签: syntax-error vb.net-2010 oledbconnection

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

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任何帮助将不胜感激。 =)

1 个答案:

答案 0 :(得分: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可以简化,BTW:

' 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行之外不会返回任何内容,因为您是没有插入任何数据?