2015-03-13 92 views
0

我在Visual Basic 2012中使用Windows窗體應用程序來使用.ADOX創建新的Microsoft Access數據庫。我可以創建數據庫,但不能在數據庫中創建表。在訪問數據庫中使用vb中的Adox創建表

我的代碼是:

Imports ADOX 
Imports System.Data.OleDb 
Public Class Form1 
Dim mycommand As OleDbCommand 
Dim myconnection As OleDbConnection 
Dim myReader As OleDbDataReader 
Dim str As String 
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click 
    Dim cat As New Catalog() 
    Dim tablename As String = "Users" 
    cat.Create("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=F:\important\DDL.mdb;Jet OLEDB:Engine Type=5") 
    cat = Nothing 
    myconnection = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=F:\important\DDL.mdb ") 
    myconnection.Open() 
    str = "CREATE TABLE [ " & tablename & "] ([Username] varchar(50)), ([Password] varchar(50)), ([E-mail] varchar(75))" 
    mycommand = New OleDb.OleDbCommand(str, myconnection) 
    mycommand.ExecuteNonQuery() 
    MsgBox("Database created") 
End Sub 
End Class 

的錯誤是得到的是:

An unhandled exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll 

Additional information: Syntax error in CREATE TABLE statement. 

任何幫助表示讚賞。

編輯: 下面的代碼獲取第一個錯誤,但我現在得到一個字段定義錯誤,我知道代碼應該工作,因爲它與添加一個數字字段,可能是因爲訪問字段類型是短文本和長文本,但我試過的任何東西似乎都不起作用。

Imports ADOX 
Imports System.Data.OleDb 
Public Class Form1 
Dim mycommand As OleDbCommand 
Dim myconnection As OleDbConnection 
Dim myReader As OleDbDataReader 
Dim str As String 
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click 
    Dim cat As New Catalog() 
    cat.Create("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=F:\important\DDL.mdb;Jet OLEDB:Engine Type=5") 
    cat = Nothing 
    myconnection = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=F:\important\DDL.mdb ") 
    myconnection.Open() 
    str = "CREATE TABLE [Users] (Username Varchar(50), Password Varchar(50), E-mail Varchar(50))" 

    mycommand = New OleDb.OleDbCommand(str, myconnection) 
    mycommand.ExecuteNonQuery() 
    MsgBox("Database created") 
End Sub 
End Class 
+0

我把問題推回去了。請不要更改原始問題 - 它會使針對該問題發佈的任何答案無效。 – LarsTech 2015-03-13 16:16:24

回答

0

看起來你有太多的parenthesizes,但我認爲實際的錯誤是從你在查詢擁有領先的空間來:

     V 
str = "CREATE TABLE [ " & tablename & "] 

嘗試將其更改爲:

str = "CREATE TABLE [" & tablename & "] ([Username] varchar(50), [Password] varchar(50), [E-mail] varchar(75))" 

請確保您處理您的物品,最好在使用區塊中:

示例:

Using cn As New OleDb.OleDbConnection(mdb) 
    cn.Open() 
    Using cmd As New OleDb.OleDbCommand(str, cn) 
    cmd.ExecuteNonQuery() 
    End Using 
End Using 
+0

謝謝,我得到的代碼工作,但我不能讓它把字段定義爲短文本(但它確實工作,如果我把字段定義爲數字)。有任何想法嗎? (我編輯我的問題與上面的新代碼即時通訊使用) – Dan 2015-03-13 16:12:11

+1

@丹你錯過了大小,就像你原來的帖子:'varchar(50)'。 – LarsTech 2015-03-13 16:15:21

+0

我試着添加大小,但我仍然得到一個字段定義錯誤,它可以被稱爲別人而不是varchar? – Dan 2015-03-16 12:47:26

相關問題