如何从visual studio填充多个访问表

时间:2012-11-16 15:26:41

标签: vb.net oledb

提前道歉 - 我是视觉工作室的新手(以及一般的编程)

我正在尝试使用以下代码填充两个访问表楼主和属性 - 但我一直在

  

“在SQL语句结束时缺少分号(;)。”

任何建议?这是代码:

Dim aConnection As OleDbConnection
Dim aCommand As OleDbCommand
Dim aConnectionString, aQuery As String
Dim Username As String = txtUsername.Text
Dim Pword As String = TextBox2.Text
Dim EmailDetails As String = TextBox9.Text
Dim Question As String = DropDownList2.Text
Dim Answer As String = TextBox4.Text

aConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source = " _
& Server.MapPath("AppData/RMT.accdb")
aConnection = New OleDbConnection(aConnectionString)
aConnection.Open()
aQuery = "Insert Into Landlord (Username, email, Security_Question, Security_Answer, Pword, Status) Values ('" & Username & "','" & EmailDetails & "','" & Question & "','" & Answer & "', '" & Pword & "','pending')Into Property Values (26,46,'marysway','MarysRd','Marysville','Cork North')"
aCommand = New OleDbCommand(aQuery, aConnection)
aCommand.ExecuteNonQuery()

aConnection.Close()

1 个答案:

答案 0 :(得分:1)

我认为Microsoft Access的ADO.NET提供程序不支持在同一个查询字符串中使用多个insert语句。但是,只是为了检查,你可以尝试写

aQuery = "Insert Into Landlord (Username, email, Security_Question, Security_Answer, " & _ 
         "Pword, Status) Values ('" & Username & "','" & EmailDetails & "','" & _
         Question & "','" & Answer & "', '" & Pword & "','pending');" & _
         "Insert Into Property Values (26,46,'marysway','MarysRd','Marysville','Cork North')"

注意第一个INSERT语句和第二个INSERT语句之间的分号(顺便说一下,原始代码中缺少第二个INSERT关键字)

说,我建议在构建要传递给数据库引擎的查询文本时使用ALVERS OleDbCommand的参数集合。
这样可以避免文本解析出现问题(输入文本中的单引号会破坏所有内容),但是,您也不会将代码公开给Sql Injection Attacks

Using aConnection = New OleDbConnection(aConnectionString)
    aConnection.Open()

    aQuery = "Insert Into Landlord (Username, email, Security_Question, " + 
             "Security_Answer, Pword, Status) Values (?, ?, ?,?,?,'pending')"
    aCommand = New OleDbCommand(aQuery, aConnection)
    aCommand.Parameters.AddWithValue("@usr", Username)
    aCommand.Parameters.AddWithValue("@email", EmailDetails)
    aCommand.Parameters.AddWithValue("@qst", Question)
    aCommand.Parameters.AddWithValue("@ans", Answer)
    aCommand.Parameters.AddWithValue("@pwd", Pword)
    aCommand.ExecuteNonQuery()

    aQuery = "Insert Into Property Values (26,46,'marysway','MarysRd','Marysville','Cork North')"
    aCommand = New OleDbCommand(aQuery, aConnection)
    aCommand.ExecuteNonQuery()

End Using