问题
I'm toast, cannot figure out why I'm getting a SYNTAX error on the line rst.Open strSQL
I've tried it with rst.Open strSQL, cnt, adOpenStatic, adLockReadOnly, adCmdText
But it still gives me an error.
I have a sneaking suspicion it has to do with how strSQL is taking a cell value and appending it to the end of a string.
Any help is highly appreciated.
Public Sub EzPz()
Dim cnt As ADODB.Connection
Dim rst As ADODB.Recordset
Set cnt = New ADODB.Connection
Set rst = New ADODB.Recordset
Dim strSQL As String
'Open connection
cnt.ConnectionString = "Driver={SQL Server};Server=HIDDEN;Database=HIDDENXX;Trusted_Connection=yes;UID=HIDDENU;PWD=HIDDENP;"
cnt.Open
'String for SQL cmd
Dim p1 As Range
Set p1 = ActiveSheet.Cells(1, 4)
strSQL = "SELECT DBNAME.vItem.Upc FROM DBNAME.vItem WHERE vItem.ItemDesc=" & p1.Value
rst.ActiveConnection = cnt
rst.Open strSQL
ActiveSheet.Cells(1, 1).CopyFromRecordset rst
End Sub
回答1:
Your code is subject to SQL injection. You could enclose the string literal in single quotes as shown in this answer to fix the syntax error, but that wouldn't fix the serious security issue.
Obligatory XKCD
So how do you securely parameterize a query? With parameterized queries!
Dim conn As ADODB.Connection
Set conn = New ADOBD.Connection
.ConnectionString = "connection string ideally using Windows Authentication"
.Open
Ideally your connection string doesn't contain any username or password; your server needs to be configured to support Windows Authentication for this to work - the query then executes with the credentials of the logged-in Windows user, with the privileges of that user.
Dim cmd As ADODB.Command
Set cmd.ActiveConnection = conn
cmd.CommandType = adCmdText
cmd.CommandText = "SELECT DBNAME.vItem.Upc FROM DBNAME.vItem WHERE vItem.ItemDesc = ?;"
Set up a Command
object. The CommandText
will be your SQL statement, but instead of concatenating the parameters into it, you use a ?
question mark for each.
Dim itemDesc As ADODB.Parameter
Set itemDesc = New ADODB.Parameter
itemDesc.Type = adVarChar
itemDesc.Direction = adParamInput
itemDesc.Value = p1.Value
cmd.Parameters.Append(itemDesc)
Create a Parameter
for each ?
question mark in the SQL statement. You must supply a parameter for each ?
question mark.
Dim results As ADODB.Recordset
Set results = cmd.Execute
You obtain the Recordset
by calling the command's Execute
method; the server deals with the parameters.
ActiveSheet.Cells(1, 1).CopyFromRecordset results
If all went well, the Recordset
contains your results.
Always use parameterized queries: user input concatenated into SQL statements is a plague.
回答2:
SQL needs to understand string literals as such; you need to delimit string literals with single quotes for the syntax to be valid.
Can you try this to see if that works?
strSQL = "SELECT DBNAME.vItem.Upc FROM DBNAME.vItem WHERE vItem.ItemDesc= '" & p1.Value & "'"
来源:https://stackoverflow.com/questions/43191113/adodb-recordset-open-giving-syntax-error-excel-to-sql