【问题标题】:Using Wildcards in SQL Query with mysql-connector-python Python 3.6在带有 mysql-connector-python Python 3.6 的 SQL 查询中使用通配符
【发布时间】:2017-09-29 13:51:45
【问题描述】:

我有一个 SQL 查询,在复制粘贴到我的 Python 代码时可以正常工作。有一行参数我想在我的 Python 脚本中创建一个变量,

AND TimeStamp like '%2017-04-17%'

所以我在 Python 脚本中设置了一个变量:

mydate = datetime.date(2017, 4, 17) #Printing mydate gives 2017-04-17

并将查询中的行更改为:

AND TimeStamp like %s

首先,当我使用粘贴在查询中的日期副本运行脚本时:cursor.execute(query) 没有错误,我可以使用cursor.fetchall() 打印结果

当我将日期设置为变量mydate 并使用%s 并尝试运行脚本时,其中任何一个都会给我一个错误:

cursor.execute(query,mydate) #"You have an error in your SQL Syntax..."   
cursor.execute(query, ('%' + 'mydate' + '%',)) #"Not enough parameters for the SQL statement"
cursor.execute(query, ('%' + 'mydate' + '%')) #"You have an error in your SQL Syntax..."
cursor.execute(query, ('%' + mydate + '%')) #"must be str, not datetime.date

"

我只想要'%2017-04-17%' %s 所在的位置。

【问题讨论】:

    标签: python mysql mysql-connector-python


    【解决方案1】:

    如果你的 MySQL 表中的值是 TIMESTAMP 类型,那么你需要做一个

    SELECT whatever FROM table where TimeStamp beween '2017-04-17' and '2017-04-18'

    创建了您的初始datetime.date 值之后,您需要在其上使用datetime.timedelta(days=1)

    【讨论】:

    • 这行得通。在日期使用通配符一直给我一个错误。谢谢。
    【解决方案2】:

    您可以在执行之前格式化查询,如下所示:

    import datetime
    mydate = datetime.date(2017,4,17)
    query="select * from table where Column_A = 'A' AND TimeStamp like '%{}%'".format(mydate)
    query
    

    query 将类似于:

    "select * from table where Column_A = 'A' AND TimeStamp like '%2017-04-17%'"
    

    之后你可以将它传递给 cursor 进行查询:

    cursor.execute(query)
    

    【讨论】:

    • 我发现我的查询有一个名称以“s”开头的通配符,所以它看起来像“%steve%”。代码将日期传递给 %s,导致出错。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-23
    • 2016-03-14
    • 1970-01-01
    • 1970-01-01
    • 2020-09-07
    • 2018-12-14
    相关资源
    最近更新 更多