在 SQL 查询中使用通配符 mysql-connector-python Python 3.6
Using Wildcards in SQL Query with mysql-connector-python Python 3.6
我有一个 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
所在的位置。
如果 MySQL table 中的值是 TIMESTAMP
类型,那么您需要执行
SELECT whatever FROM table where TimeStamp beween '2017-04-17' and '2017-04-18'
创建初始 datetime.date
值后,您需要对其使用 datetime.timedelta(days=1)
。
您可以像这样在执行之前格式化您的查询:
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)
我有一个 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
所在的位置。
如果 MySQL table 中的值是 TIMESTAMP
类型,那么您需要执行
SELECT whatever FROM table where TimeStamp beween '2017-04-17' and '2017-04-18'
创建初始 datetime.date
值后,您需要对其使用 datetime.timedelta(days=1)
。
您可以像这样在执行之前格式化您的查询:
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)