Or instead of using a direct sql Statement,use Preparaed sql Statements. When you execute a prepared sql statement,you don't have to worry about special characters in your Text. Prepared Statements will automatically take care of the Single Quote and other symbols.
Moreover Prepared Statements are better that the sql Statements that are insertted in the code,they are faster and reduce the chances of sql Injection attacks.
Here is a simple example of how to use Command Object and Preparaed sql Statements
CODE:
Dim cmdsqlInsert As ADODB.Command
Set cmdsqlInsert = New ADODB.Command
'Create the query
cmdsqlInsert.CommandText = "Insert Into Table1(ID,NAME,AGE) Values(?,?,?)"
cmdsqlInsert.CommandType = adCmdText
cmdsqlInsert.Prepared = True
'Create the parameters
'in this case we will create three parameters
'-----Param 1 (for Field ID)-------------
Dim gParam As ADODB.Parameter
Set gParam = New ADODB.Parameter
With gParam
.Name = "ID"
.Direction = adParamInput
.Type = adChar
.Size = 10
.Value = "xxxxxxxxxx"
End With
cmdsqlInsert.Parameters.Append gParam
'-----Param 2 (for Field Name)-------------
Set gParam = Nothing
Set gParam = New ADODB.Parameter
With gParam
.Name = "NAME"
.Direction = adParamInput
.Type = adVarChar
.Size = 50
.Value = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
End With
cmdsqlInsert.Parameters.Append gParam
'-----Param 3 (for Field AGE)-------------
Set gParam = Nothing
Set gParam = New ADODB.Parameter
With gParam
.Name = "AGE"
.Direction = adParamInput
.Type = adChar
.Size = 2
.Value = "xx"
End With
cmdsqlInsert.Parameters.Append gParam
'Set the connection property of the command object
Set cmdsqlInsert.ActiveConnection = MysqLConnection
'pass the values that need to be inserted to specific parameters that we created above
cmdsqlInsert("ID") = txtID.Text
cmdsqlInsert("NAME") = txtName.Text
cmdsqlInsert("AGE") = txtAge.Text
'Execute the command
cmdsqlInsert.Execute
Remember once the Prepared Statement is built,next time you just need to pass on the values for the Parameters and execute the statement. This makes code look more handsome and easily maintainable. You could also look in MSDN for more about Preparaed Statements and search this forum too.
原文链接:https://www.f2er.com/vb/258667.html