简体   繁体   English

使用 Excel 单元格中的值作为 SQL 查询中 WHERE 子句的条件

[英]Use value in Excel cell as condition for WHERE clause in SQL query

Sub Get_Data()

Dim conn As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim dateVar As Date

    Set conn = New ADODB.Connection
    conn.ConnectionString = "DRIVER={MySQL ODBC 5.1 Driver}; SERVER=localhost; DATABASE=bi; UID=username; PWD=password; OPTION=3"
    conn.Open

                strSQL = " SELECT " & _
                            " Products " & _
                            " FROM Logistics " & _
                            " WHERE DATE(insert_timestamp) = ""2020-02-24"" " & _
                            " GROUP BY 1"

    Set rs = New ADODB.Recordset
    rs.Open strSQL, conn, adOpenStatic

    Sheet5.Range("A1").CopyFromRecordset rs

    rs.Close
    conn.Close

End Sub

I run the above VBA to extract values fom the database .我运行上面的VBAdatabase提取值。
It works exactly how I need it.它完全按照我的需要工作。


Now, instead of having a pre-defined date within strSQL I want to use the data that is entered into Cell B1 in my Excel spreadsheet.现在,我想使用在 Excel 电子表格中的Cell B1中输入的数据,而不是在strSQL中使用预定义的日期。 Therefore, I changed the strSQL part in the VBA to:因此,我将VBAstrSQL部分更改为:

        strSQL = " SELECT " & _
                    " Products " & _
                    " FROM Logistics " & _
                    " WHERE DATE(insert_timestamp) = " & Sheet1.Range("B1") & " " & _
                    " GROUP BY 1"

However, now I get runtime error -2147217887 (80040e21) on rs.Open strSQL, conn, adOpenStatic .但是,现在我在rs.Open strSQL, conn, adOpenStatic上收到runtime error -2147217887 (80040e21)

What do I need to change in my VBA to make it work?我需要在VBA更改什么才能使其正常工作?

Consider the industry best practice of SQL parameterization using the ADO Command object which can properly handle data types without string concatenation or various formatting:考虑使用ADO 命令对象的SQL 参数化的行业最佳实践,该对象可以正确处理数据类型而无需字符串连接或各种格式:

Dim conn As ADODB.Connection      ' REMOVE New INITIALIZATION IN Dim LINES
Dim rs As ADODB.Recordset
Dim cmd As ADODB.Command
Dim dateVar As Date

Set conn = New ADODB.Connection
conn.ConnectionString = "DRIVER={MySQL ODBC 5.1 Driver}; ..."
conn.Open

' STRING STATEMENT WITH QMARK PLACEHOLDER
strSQL = " SELECT " & _
             "   Products " & _
             " FROM Logistics " & _
             " WHERE DATE(insert_timestamp) = ?" & _
             " GROUP BY Products"

' CONVERT CELL TO DATE TYPE (IF CELL FORMATTED AS STRING)
dateVar = CDate(Sheet1.Range("B1").Value)

Set cmd = New ADODB.Command

With cmd
   .ActiveConnection = conn
   .CommandText = strSQL
   .CommandType = adCmdText

   ' BIND PARAMS TO QMARK POSITIONAL PLACEHOLDER
   .Parameters.Append .CreateParameter("mydate", adDate, adParamInput, , dateVar)

   ' PASS RESULT TO RECORDSET
   Set rs = .Execute
End With

Sheet5.Range("A1").CopyFromRecordset rs

Try:尝试:

strSQL =    " SELECT " & _
            " Products " & _
            " FROM Logistics " & _
            " WHERE DATE(insert_timestamp) = '" & Format(Sheet1.Range("B1").Value, "YYYY-MM-DD") & "' " & _
            " GROUP BY 1"

Just be aware, if insert_timestamp does indeed contain a time other than midnight, you might not get the results you're after without converting to just a date or altering your SQL.请注意,如果insert_timestamp确实包含午夜以外的时间,则如果不转换为日期或更改 SQL,您可能无法获得所需的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM