2

我想使用 vb.net 创建一个带有 SQL 查询的表。我使用以下代码:

dBaseConnection.Open()
sql = "DROP TABLE TagSubs;" &
      "CREATE TABLE TagSubs (TAGNAME varchar(79), POLLTIME varchar(6), SCALEMODE varchar(8), DEADBAND varchar(15))"
Dim dBaseCommand As New System.Data.OleDb.OleDbCommand(sql, dBaseConnection)
dBaseCommand.ExecuteNonQuery()
dBaseCommand = Nothing
dBaseConnection.Close()

出于某种原因,如果我省略该行:

 "DROP TABLE TagSubs;" 

应用程序第一次很好地创建了表。但是我第二次执行它时,它告诉我表已经存在并抛出一个错误。这就是为什么我添加了 drop table 部分。

对我来说不幸的是,这给了我一个适用于“DROP TABLE or DROP INDEX”的语法错误

我究竟做错了什么 ?


编辑1:

我得到的错误信息如下(大致从荷兰语翻译而来):

The instruction DROP TABLE or DROP INDEX contains a syntaxerror

视觉工作室提供的唯一帮助是:

Get general help for this exception 

Wich根本没有任何帮助!


编辑2:

在史蒂夫和米奇的评论之后,我将代码更改为:

sql = "DROP TABLE IF EXISTS TagSubs"
dBaseCommand = New System.Data.OleDb.OleDbCommand(sql, dBaseConnection)
dBaseCommand.ExecuteNonQuery()
dBaseCommand = Nothing

sql = "CREATE TABLE TagSubs (TAGNAME varchar(79), POLLTIME varchar(6), SCALEMODE varchar(8), DEADBAND varchar(15))"
dBaseCommand = New System.Data.OleDb.OleDbCommand(sql, dBaseConnection)
dBaseCommand.ExecuteNonQuery()
dBaseCommand = Nothing
dBaseConnection.Close()

但是,这给出了错误:

"An invalid SQL instruction was found. DELETE,INSERT, PROCEDURE, SELECT or UPDATE was expected"
4

2 回答 2

3

假设这些命令在连接在一起的时候还不是很好理解,我会尝试将它们分开执行两个不同的查询,然后用两个不同的运行执行这两个 sql 命令。

仅当表存在时才应执行删除表的命令。在 DBF 中,表通常包含在一个简单的操作系统文件中。所以检查文件是否存在就足够了。

dBaseConnection.Open()
Dim dBaseCommand As New System.Data.OleDb.OleDbCommand()
dBaseCommand.Connection = dBaseConnection
if File.Exists(... insert path here .... "\TagSubs.DBF") Then
    sql = "DROP TABLE TagSubs"
    dBaseCommand.CommandText = sql
    dBaseCommand.ExecuteNonQuery()
End If
sql="CREATE TABLE TagSubs (TAGNAME varchar(79), POLLTIME varchar(6), SCALEMODE varchar(8), DEADBAND varchar(15))"
dBaseCommand.CommandText = sql
dBaseCommand.ExecuteNonQuery()
dBaseCommand = Nothing
dBaseConnection.Close()
于 2013-04-22T08:48:06.777 回答
0

试试这个并把你的程序放下:

Dim rsSchema As ADODB.Recordset
rsSchema = New ADODB.Recordset

rsSchema = conn.OpenSchema(ADODB.SchemaEnum.adSchemaColumns, New Object() {Nothing, Nothing, **tablename**, Nothing})
'MsgBox(rsSchema)

If rsSchema.BOF And rsSchema.EOF Then
    MsgBox("Table does not exist")
Else
    MsgBox("Table exists")
End If
rsSchema.Close()
rsSchema = Nothing

像这样的连接:

Public Sub modOpen()

    Msg = "Provider=SQLOLEDB.1; Persist Security Info=False;" & Chr(10)
    Msg = Msg & "password=******;Data Source=**KOMPUTERNAME**;Initial Catalog=**DATABASENAME**;User ID=**USERID**"


    Try
        conn = New Adodb.Connection
        conn.ConnectionString = Msg

    Catch ex As Exception
        MsgBox("Error: " & ex.Source & ": " & ex.Message, MsgBoxStyle.OkOnly, "Connection Error!!")

    End Try


End Sub

它适用于 VB.NET2010

于 2015-03-10T12:10:56.907 回答