简体   繁体   English

将变量值传递给for循环中的查询

[英]Pass variable value to query in for loop

I have a list comprised of several queries which are executed by a for loop.我有一个由几个查询组成的列表,这些查询由 for 循环执行。 I would like to prompt the user to enter the origin (ilink) that will be utilized by the fourth query in the list.我想提示用户输入列表中第四个查询将使用的来源(ilink)。

The script runs fine when the origin is manually defined within the query.当在查询中手动定义原点时,脚本运行良好。 I have tried the following syntax which have all failed:我尝试了以下所有失败的语法:

cursor.execute(lines, ilink)
cursor.execute(lines, [ilink])
cursor.execute(lines, (ilink))

I have also run the script with each query defined in its own cursor.execute(query) which accepts the argument, but does not pass any results due to multiple cursors.我还运行脚本,每个查询在其自己的 cursor.execute(query) 中定义,它接受参数,但由于多个游标不传递任何结果。

import MySQLdb
ilink = raw_input("Choose and ilink to query (include 199N):" )
db = MySQLdb.connect(host="host",user="user",passwd="pass")
queries = [
"""USE monthly_audit;""",
"""DROP TEMPORARY TABLE IF EXISTS monthly_audit.tmp_order_ids;""",
"""DROP TEMPORARY TABLE IF EXISTS monthly_audit.tmp_internalselect;""",
"""CREATE TEMPORARY TABLE monthly_audit.tmp_order_ids AS
(SELECT DISTINCT order_id AS orders
FROM ng_tradeserver_db_history.fix_execution_reports_201906
WHERE FROM_UNIXTIME(TIMESTAMP/1000000) >=  '2019-06-19 16:59:59'
AND FROM_UNIXTIME(TIMESTAMP/1000000) <= '2019-06-20 23:59:59'
AND TargetCompID = %s);""",]
cursor = db.cursor()
for lines in queries:
    lines.split(",")
    cursor.execute(lines, [ilink])
results = cursor.fetchall()

**This is only the relevant snippet of sql, total query is over 500 lines* **这只是sql的相关片段,总查询超过500行*

I expect the script to run the set of queries and return the results of said query to be stored in a csv.我希望脚本运行查询集并将所述查询的结果返回存储在 csv 中。 I am currently getting the following error when executing: _mysql_exceptions.ProgrammingError: not all arguments converted during string formatting我目前在执行时收到以下错误:_mysql_exceptions.ProgrammingError: not all arguments conversion during string formatting

I'm not sure if I understand your questions correct, but you can try using fstrings.我不确定我是否理解您的问题是否正确,但您可以尝试使用 fstrings。 I believe the quotes cause the problems during the string formatting.我相信引号会导致字符串格式化期间出现问题。

Example:例子:

query = f'''select ID, lat, lon from tbl order by st_distance(tbl.geom,st_setsrid(st_makepoint({lon},{lat}), 4326)) asc limit 1;'''
cursor.execute(query)

In this query the {lon}, {lat} are variables.在这个查询中,{lon}、{lat} 是变量。 Have a look at the docs for f strings https://docs.python.org/3/whatsnew/3.6.html查看 f 字符串https://docs.python.org/3/whatsnew/3.6.html的文档

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

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