Python fdb编写的语句列表

时间:2013-09-13 12:01:33

标签: python firebird fdb

是否可以在Python的fdb库中添加列表作为预处理语句参数?

示例:

cur = con.cursor()
list = [1,2,3]
cur.execute("""SELECT * FROM data d WHERE d.field IN ?""", (list,))

结果:

"Error while preparing SQL statement:")\nDatabaseError: (\'Error while preparing SQL      statement:\\n- SQLCODE: -104\\n- Dynamic SQL Error\\n- SQL error code = -104\\n- Token unknown - line 4, column 33\\n- ?\', -104, 335544569)\n'

有没有已知的解决方案? 提前致谢

4 个答案:

答案 0 :(得分:1)

列表不能用作参数化查询的值,您需要自己构建它,方法是动态创建一个包含所有列表项的足够占位符的查询,或者使用列表中的文字值。

答案 1 :(得分:0)

试试这样。

cur.execute("""SELECT * FROM data d WHERE d.field IN %s """, (tuple(list), ))

答案 2 :(得分:0)

理解这是一个古老的问题,将来的访问者应该知道,如果对列表中的字符串(而不是整数)使用以上和注释中的答案,则可能存在SQL注入的风险。我尚未创建表来专门测试下面的代码,但在其他查询中使用了类似的代码。

仅供参考-其他SQL驱动程序(例如pyodbc和psycopg2)使用'%s'作为占位符,但仅使用'? '使用fdb为我工作。

cur = con.cursor()
list = [1,2,3]

# Create a placeholder list containing a '?' for each element
placeholders = []
for i in list:
    placeholders.append('?')
# Change placeholder list to string of question marks separated by commas
ph_text = ', '.split(placeholders)

# Create sql statement
# Can use format here without risk of SQL injection because it is only ', ' and '?'
sql = """SELECT * FROM data d WHERE d.field IN ({0})""".format(ph_text)

# Execute the statement, passing list items in tuple for fdb to escape (avoid SQL-injection)
# Note that the list is converted to a tuple, 
# whereas the SQL in the question had the list as the first (and only) tuple element
cur.execute(sql, tuple(list))

答案 3 :(得分:-1)

是的,但你的语法错了,Firebird需要接收

SELECT * FROM data d WHERE d.field IN (1,2,3)所以我过去(来自记忆)

完成了这项工作

stmt="SELECT * FROM data d WHERE d.field IN (" + list + ")" cur.execute(stmt)