创建新的访问表并从文本框中命名

时间:2015-12-23 09:32:39

标签: vb.net ado.net

我正在尝试在数据库中创建新的访问表,但是当我尝试从文本框中命名时,它会给出错误

Sub CreateTable()

Dim strCreate As String = "CREATE TABLE"& TxtBoxTb1Name.Text &(" & _

“CountryName varchar(120)主键”,& _         “大陆整数”,& _         “区域长”,& _         “人口长”,& _         “Capital varchar(80),”& _         “Code char(2));”

    Dim conDatabase As OleDbConnection = New OleDbConnection("Provider=Microsoft.JET.OLEDB.4.0;" & _
    "Data Source=""Data Source=" & filename & ".mdb;")
    Dim cmdDatabase As OleDbCommand = New OleDbCommand(strCreate, conDatabase)
    conDatabase.Open()
    cmdDatabase.ExecuteNonQuery()
    conDatabase.Close()
    MessageBox.Show("Table Created Sucessfully")
End Sub

1 个答案:

答案 0 :(得分:0)

您必须修改sintax以定义主键,并在创建SQL语句时注意空格和逗号。以下是有效的固定代码。

导入System.Data.OleDb 进口System.IO 公共类Form1     私有文件名As String =" SampleDB.mdb"

Private Sub CreateTable()
    Dim strCreate As String = "CREATE TABLE " &
        TxtBoxTb1Name.Text & "(_Continent Integer, " & "_Area Long, " & "_Population Long," & "_Capital varchar(80)," & "_Code Char(2)," & "_CountryName varchar(120) CONSTRAINT MyFieldConstraint PRIMARY KEY)"

    Dim conDatabase As OleDbConnection = New OleDbConnection("Provider=Microsoft.JET.OLEDB.4.0; " &
        "Data Source=" & Path.GetFullPath(filename) & "; User Id=admin;
        Password =;")
    conDatabase.Open()
    Dim cmdDatabase As OleDbCommand = New OleDbCommand(strCreate, conDatabase)

    cmdDatabase.ExecuteNonQuery()
    conDatabase.Close()
    MessageBox.Show("Table Created Sucessfully")

End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    CreateTable()
End Sub

结束班