Excel ODBC链接到SQL查询以获取日期之间的结果

时间:2019-06-12 07:29:51

标签: mysql excel vba odbc

我正在Windows 10 Pro计算机上运行Excel 2016。我已经建立了从Excel到外部MariaDB SQL数据库的ODBC连接。我的VBA宏主要按照我想要的方式工作,但是在两个日期之间选择记录时遇到了问题。此SQL语句有效:

SELECT Date_Time, ChargerSt FROM `MyDBx`.`table` WHERE (Date_Time>{ts '2019-06-01 00:00:00'}) ORDER BY Date_Time;

但是,我无法使用WHERE来获得BETWEEN date1 AND date2子句的任何组合;以上与Date_Time<{ts '2019-06-11 00:00:00'}结合使用。 Date_Time的SQL数据库中yyyy-mm-dd的格式。

我正在输入如下日期:

firstdate = InputBox("Enter starting date (yyyy-mm-dd)")
seconddate = Format((DateValue(firstdate) - 7#), "yyyy-mm-dd")

SQL语句的VBA代码如下所示

"SELECT Date_Time, ChargerSt FROM `MyDBx`.`table` " _
 & "WHERE (Date_Time>{ts '" & firstdate & " 00:00:00'})" & " ORDER BY Date_Time"

这可能真的很简单,仅显示出我缺乏SQL经验,但我正在尝试学习。

1 个答案:

答案 0 :(得分:1)

在解决您的情况时,请考虑在ODBC连接中进行参数化,这是在VBA等应用程序层上运行SQL的首选方式。通过参数化,您可以避免连接或标点的需要,并且在一般编程行业中建议在VBA(例如Java,Python,PHP)或MariaDB(Oracle,SQL Server,Postgres)之外使用。

以下假设您在Excel中使用ADO并在模块上运行后期绑定。

Public Sub RunSQL()   
    Dim firstdate As Date, seconddate As Date
    Dim sql as String, conn As Object, cmd As Object, rst As Object
    Const adCmdText = 1, adParamInput = 1, adDate = 7

    firstdate = DateValue(InputBox("Enter starting date (yyyy-mm-dd)"))
    seconddate = firstdate - 7

    Set conn = CreateObject("ADODB.Connection")
    Set rst = CreateObject("ADODB.Recordset")

    conn.Open "Driver={MySQL ODBC 5.3 Unicode Driver};host=hostname;" _
               & "database=databasename;UID=username;PWD=****"

    ' PREPARED STATEMENT (NO DATA)
    sql = "SELECT Date_Time, ChargerSt FROM `MyDBx`.`table` WHERE `DateTime` BETWEEN ? AND ?"
    ' CONFIGURE ADO COMMAND
    Set cmd = CreateObject("ADODB.Command")
    With cmd
        .ActiveConnection = conn
        .CommandText = sql
        .CommandType = adCmdText
        ' BIND DATE VALUES
        .Parameters.Append .CreateParameter("start_param", adDate, adParamInput, , firstdate)
        .Parameters.Append .CreateParameter("start_param", adDate, adParamInput, , seconddate)
        ' CREATE RECORDSET
        Set rst = .Execute
    End With

    '... USE RECORDSET

    rst.Close
    Set rst = Nothing: Set cmd = Nothing: Set conn = Nothing    
End Sub