这是我试图将数据插入数据库的代码片段。我没有收到任何语法错误,但它没有提交数据。
Sub submit(ByVal sender As Object, ByVal e As EventArgs)
Dim objConn As New OleDbConnection
Dim objCmd As New OleDbCommand
Dim strConnString, strSQL As String
strConnString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source= " & Server.MapPath("Mydatabase.mdb") & ""
strSQL = "INSERT INTO tblRecord (CNIC,Names,City,Address,Number) " & " VALUES " & " ('" & cnic.Text & "','" & name.Text & "','" & city.Text & "','" & postal.Text & "','" & phone.Text & "')"
objConn.ConnectionString = strConnString
objConn.Open()
With objCmd
.Connection = objConn
.CommandText = strSQL
.CommandType = CommandType.Text
End With
Try
objCmd.ExecuteNonQuery()
Label1.Text = "Record Inserted Sucessfully."
Label1.Visible = True
Catch ex As Exception
Label1.Visible = True
Label1.Text = "Record Cannot Insert" & ex.ToString()
End Try
objConn.Close()
End Sub
这是我得到的例外:
System.Data.OleDb.OleDbException:INSERT INTO语句中的语法错误。
at System.Data.OleDb.OleDbCommand.ExecuteCommandTextErrorHandling(OleDbHResult hr)
System.Data.OleDb.OleDb.OleDb.OleDbCommand.ExecuteCommandText(Object& executeResult)的System.Data.OleDb.OleDbCommand.ExecuteCommandTextForSingleResult(tagDBPARAMS dbParams,Object& executeResult) 在System.Data.OleDb.OleDbCommand.ExecuteCommand(CommandBehavior behavior,Object& executeResult)
在System.Data.OleDb.OleDbCommand.ExecuteReaderInternal(CommandBehavior behavior,String method)
在System.Data.OleDb.OleDbCommand.ExecuteNonQuery()
at ASP.registration_aspx.submit(Object sender,EventArgs e)在C:\ Documents and Settings \ Maira Alvi \ My Documents \ Visual Studio 2005 \ WebSites \ WebSite3 \ Registration.aspx:line 32
答案 0 :(得分:1)
我的猜测是你的一个输入字段包含一个非转义字符(例如'
)。切换到参数化查询不仅可以解决该问题,还可以防止其他问题(如SQL注入)。
//change query to use parameters
strSQL = "INSERT INTO tblRecord (CNIC,Names,City,Address,Number) VALUES (?,?,?,?,?);"
...
With objCmd
.Connection = objConn
.CommandText = strSQL
.CommandType = CommandType.Text
//add parameters using inputs for values
.Parameters.Add("?", OleDbType.VarChar, 50).Value = cnic.Text; //assumes varchar(50)
.Parameters.Add("?", OleDbType.VarChar, 50).Value = name.Text; //assumes varchar(50)
.Parameters.Add("?", OleDbType.VarChar, 50).Value = city.Text; //assumes varchar(50)
.Parameters.Add("?", OleDbType.VarChar, 50).Value = postal.Text; //assumes varchar(50)
.Parameters.Add("?", OleDbType.VarChar, 50).Value = phone.Text; //assumes varchar(50)
End With
答案 1 :(得分:0)
你有一个语法错误,它在你的异常中就这么说了!看一下您为SQL Insert语句构建的字符串。我很确定某处有一个'
缺失。
但基本上,这是构建SQL语句的一种非常糟糕的方法。它可以通过使用string.Format来改进,但即使这样你也会接受SQL注入攻击。
使用参数添加值要好得多。 Here's an example of how to do it right.