Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/63.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python-使用Python参数对查询应用筛选器_Python_Mysql_Filter_Cursor - Fatal编程技术网

Python-使用Python参数对查询应用筛选器

Python-使用Python参数对查询应用筛选器,python,mysql,filter,cursor,Python,Mysql,Filter,Cursor,我有一个脚本,可以在MySQL上查询我的数据库。我的疑问是,我是否可以通过Python向该查询传递任何参数 例如,在下面的脚本中,我想使用Python计算date_过滤器,然后将该过滤器应用于查询 now = dt.datetime.now() date_filter = now - timedelta(days=3) dq_connection = mysql.connector.connect(user='user', password='pass', host='localhost',

我有一个脚本,可以在MySQL上查询我的数据库。我的疑问是,我是否可以通过Python向该查询传递任何参数

例如,在下面的脚本中,我想使用Python计算date_过滤器,然后将该过滤器应用于查询

now = dt.datetime.now()
date_filter = now - timedelta(days=3)

dq_connection = mysql.connector.connect(user='user', password='pass', host='localhost', database='db')
engine = create_engine('localhost/db')
cursor = connection.cursor(buffered=True)
query = ('''
SELECT *
FROM myTable
WHERE date >= ''' + date_filter + '''
''')
我用这种方法尝试了一下,但出现了以下错误:

builtins.TypeError: can only concatenate str (not "datetime.datetime") to str
可以这样使用过滤器吗


谢谢

您可以执行以下操作:

其中日期>='+strdate_过滤器+' 要将日期表示为字符串而不是datetime对象,请尝试以下操作:

date_f = str(date_filter)

query = ('''
SELECT *
FROM myTable
WHERE date >= "{}"
'''.format(date_f))

是的,你能做到。为了避免sql注入,最好的方法是不使用python格式化工具,但sql参数和占位符会看到,在占位符执行任务并转换变量类型时,您不需要单引号:

now = dt.datetime.now()
date_filter = now - timedelta(days=3)

dq_connection = mysql.connector.connect(user='user', password='pass', host='localhost', database='db')
engine = create_engine('localhost/db')
cursor = db_connection.cursor(buffered=True)
query = "SELECT * FROM myTable WHERE date >=%s"
cursor.execute(query,(date_filter,))
另外,您的游标有一个错误,应该是db_connection.cursor。date_过滤器后面的最后一个逗号是ok的,因为您需要发送一个元组。 如果需要多个参数,可以放置多个占位符:

query = "SELECT * FROM myTable WHERE date >=%s and date<=%s"
cursor.execute(query,(date_filter,other_date))

回答:非常感谢!如果不是cursor.execute,而是想将数据传递到一个数据帧:df=pd.read\u sql\u queryquery,connection,我可以用同样的方法来做吗?是的,你可以用pd.read\u sql\u queryquery,connection,params=date\u filter来做,。你可以把所有的信都读出来