将变量值传递给 for 循环中的查询
Pass variable value to query in for loop
我有一个由多个查询组成的列表,这些查询由 for 循环执行。我想提示用户输入列表中第四个查询将使用的来源 (ilink)。
当原点在查询中手动定义时,脚本 运行 没问题。我尝试了以下语法,但都失败了:
cursor.execute(lines, ilink)
cursor.execute(lines, [ilink])
cursor.execute(lines, (ilink))
我还有 运行 脚本,每个查询都在其自己的 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()
**这只是 sql 的相关片段,总查询超过 500 行*
我希望脚本 运行 查询集和 return 所述查询的结果存储在 csv 中。我目前在执行时遇到以下错误:
_mysql_exceptions.ProgrammingError: 并非所有参数在字符串格式化期间都已转换
我不确定我是否理解你的问题,但你可以尝试使用 fstrings。我相信引号会导致字符串格式化过程中出现问题。
示例:
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)
在此查询中,{lon}、{lat} 是变量。查看 f 字符串的文档 https://docs.python.org/3/whatsnew/3.6.html
我有一个由多个查询组成的列表,这些查询由 for 循环执行。我想提示用户输入列表中第四个查询将使用的来源 (ilink)。
当原点在查询中手动定义时,脚本 运行 没问题。我尝试了以下语法,但都失败了:
cursor.execute(lines, ilink)
cursor.execute(lines, [ilink])
cursor.execute(lines, (ilink))
我还有 运行 脚本,每个查询都在其自己的 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()
**这只是 sql 的相关片段,总查询超过 500 行*
我希望脚本 运行 查询集和 return 所述查询的结果存储在 csv 中。我目前在执行时遇到以下错误: _mysql_exceptions.ProgrammingError: 并非所有参数在字符串格式化期间都已转换
我不确定我是否理解你的问题,但你可以尝试使用 fstrings。我相信引号会导致字符串格式化过程中出现问题。
示例:
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)
在此查询中,{lon}、{lat} 是变量。查看 f 字符串的文档 https://docs.python.org/3/whatsnew/3.6.html