我想使用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或DROP INDEX”的语法错误
我做错了什么?
编辑1:
我得到的错误信息如下(大致翻译自荷兰语):
The instruction DROP TABLE or DROP INDEX contains a syntaxerror
视觉工作室提供的唯一帮助是:
Get general help for this exception
根本没有任何帮助!
编辑2:
在Steve和Mitch的评论之后,我已将代码更改为:
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"
答案 0 :(得分:2)
假设这些命令在连接在一起时没有被很好地理解,我将尝试将它们分开执行两个不同的查询,然后用两个不同的运行执行两个sql命令。
只有表存在时才应执行DROP表的命令。在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()
答案 1 :(得分: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