这是我在VB.NET中的代码。
我的try catch表示指令INSERT INTO
中存在语法错误。我不知道我的INSERT发生了什么。我搜索了一个多小时的错误......我不是VB.NET的专家,我在C#方面做得更好,但无论如何我都需要在VB中这样做...
谢谢你的帮助!!
Sub InsertRecord()
Dim conClasf As OleDbConnection
Dim cmdClasf As New OleDbCommand
Dim strClasf As String
Dim strSQL As String
Dim intRowsAff As Integer
lblErrMsg.Text = ""
lblRecsAff.Text = ""
strClasf = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & _
server.mappath("BecsEtMuseaux.mdb") & ";"
conClasf = New OleDbConnection(strClasf)
conClasf.Open
Randomize
strSQL = "INSERT INTO client (" & _
"UserName, " & _
"Prenom, " & _
"Nom, " & _
"password, " & _
"mail, " & _
"Addresse, " & _
"Ville, " & _
"PostalCode, " & _
"Province, " & _
"Pays, " & _
"AnimalGenre, " & _
"NomAnimal, " & _
"Race, " & _
") VALUES ('" & _
Replace(txtUserName.Text, "'", "''") & _
"', '" & _
Replace(txtPrénom.Text, "'", "''") & _
"', '" & _
Replace(txtNom.Text, "'", "''") & _
"', '" & _
Replace(txtPass.Text, "'", "''") & _
"', '" & _
Replace(txtMail.Text, "'", "''") & _
"', " & _
Replace(txtAdresse.Text, "'", "''") & _
"', " & _
Replace(txtVille.Text, "'", "''") & _
"', " & _
Replace(txtPostal.Text, "'", "''") & _
"', " & _
Replace(txtProvince.Text, "'", "''") & _
"', " & _
Replace(txtPays.Text, "'", "''") & _
"', " & _
Replace(rblAnimal.Text, "'", "''") & _
"', " & _
Replace(txtAnimal.Text, "'", "''") & _
"', " & _
Replace(txtRace.Text, "'", "''")
cmdClasf = New OleDbCommand(strSQL, conClasf)
Try
intRowsAff = cmdClasf.ExecuteNonQuery()
Catch ex As Exception
lblErrMsg.Text = ex.Message
End Try
lblRecsAff.Text = intRowsAff & " record(s) inserted"
conClasf.Close
End Sub
答案 0 :(得分:2)
转义密码字段。它是Access Engine.的保留字。
strSQL = "INSERT INTO client (UserName,Prenom,Nom,[password],mail,
Addresse,Ville,PostalCode,Province,Pays,AnimalGenre,NomAnimal,Race)
VALUES
(@UserName,@Prenom,@Nom,@password,@mail,
@Addresse,@Ville,@PostalCode,@Province,@Pays,
@AnimalGenre,@NomAnimal,@Race)"
答案 1 :(得分:1)
这可能会导致错误。
"Race, " & _ //Race**,** try to remove ,
")
如果你这样做会好多了:
您可以使用参数来避免sqlinjection。
strSQL = "INSERT INTO client (UserName,Prenom,Nom,password,mail,Addresse,Ville,PostalCode,Province,Pays,AnimalGenre,NomAnimal,Race) VALUES (@UserName,@Prenom,@Nom,@password,@mail,@Addresse,@Ville,@PostalCode,@Province,@Pays,@AnimalGenre,@NomAnimal,@Race)"
cmdClasf.Parameters.Add("@UserName", OleDbType.VarChar, 50).Value = txtUserName.Text
//DO OTHER STUFF UNITL @Race
另见:
Parameter Queries in ASP.NET with MS Access
Configuring Parameters and Parameter Data Types (ADO.NET)
Use Parameters in your sql command
希望得到这个帮助。
此致