Python 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'

是否有任何已知的解决方案?提前致谢

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

试试这样。

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

理解这是一个老问题,未来的访问者应该知道,如果将上面的答案和评论中的答案用于列表中的字符串而不仅仅是整数,可能会带来一些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))

是的,但你的语法是错误的,火鸟需要接收

SELECT * FROM data d WHERE d.field IN (1,2,3)所以我过去已经这样做了(从记忆中)

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

最新更新