命名访问表从文本框的文本

时间:2015-12-23 10:01:21

标签: vb.net

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

Sub CreateTable()

 Dim strCreate As String = "CREATE TABLE" & TxtBoxTblName.Text &(" & _
    "CountryName varchar(120) Primary key," & _
    "Continent Integer," & _
    "Area Long," & _
    "Population Long," & _
    "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)

我猜你错过了这一行"中的"CREATE TABLE" & TxtBoxTblName.Text &(" & _,这些CREATE TABLE关键字后面的空格也会产生错误。所以它应该是"CREATE TABLE " & TxtBoxTblName.Text &"(" & _看到差异here 尝试下面的代码

Dim STR_DDL As String
STR_DDL = "CREATE TABLE #TABLENAME# (CountryName varchar(120) Primary key,Continent Integer,Area Long,Population Long,Capital varchar(80),Code char(2));"
STR_DDL.Replace("#TABLENAME#", Trim(TxtBoxTblName.Text))

<强> OR

使用Composite Formatting

Dim STR_DDL As String = String.Format("CREATE TABLE {0} (CountryName varchar(120) Primary key " & _
                                ",Continent Integer,Area Long,Population Long,Capital varchar(80) " & _
                                ",Code char(2));", Trim(TxtBoxTblName.Text))

{0}TxtBoxTblName.Text

的占位符

并使用它

Dim cmdDatabase As OleDbCommand = New OleDbCommand(STR_DDL , conDatabase)