如何将python变量传递到sqlite3查询中?[duplicate]

sxissh06  于 2022-12-19  发布在  SQLite
关注(0)|答案(1)|浏览(146)
    • 此问题在此处已有答案**:

(13个答案)
How to use variables in SQL statement in Python?(5个答案)
六年前关闭了。
代码应该基于Python环境中用户的输入执行查询(而不是在sql查询中)。例如,变量是在Python环境中定义的,在table name = customers的原始输入中,我希望查询打印表customers的列名。
但是,下面的代码报告了语法错误。如果我删除反斜杠和内引号,它将报告no such column: table_name。看起来值customers没有被传递到查询中,查询将table_name读取为字符串。
帮帮忙。谢谢

import sqlite3

    def ask_column(db_name, table_name):
        conn = sqlite3.connect(db_name)
        c = conn.cursor()
        c.execute('SELECT sql FROM sqlite_master WHERE type = \'table\' And name = \'table_name\'') 
        print c.fetchall()
        conn.close()

db_name = raw_input("Please type the database name : ")
table_name = raw_input("Please type the table name: ")
ask_column(db_name, table_name)
jljoyd4f

jljoyd4f1#

你可以使用参数替换来完成这个操作。当使用Python's sqlite3 module时,用问号(?)替换你的参数值,并提供一个值的 * 元组**。Python会自动处理替换,并转义值以限制SQL注入的风险。
下面是一个例子:首先,创建一个表:

>>> import sqlite3
>>> c = conn.cursor()
>>> c.execute("""CREATE TABLE test (fruit, colour)""")
<sqlite3.Cursor object at 0x7f41e929f650>

现在插入一些值:注意?字符是如何用作值的占位符的:

>>> c.executemany("""INSERT INTO test VALUES (?, ?)""", [('apple', 'green'), ('banana', 'yellow'), ('cherry', 'red')])
<sqlite3.Cursor object at 0x7f41e929f650>

下面是一个查询(注意,我们将值作为元组传递,即使只有一个值):

>>> c.execute("""SELECT fruit, colour FROM test WHERE fruit = ?;""", ('apple',)) 
<sqlite3.Cursor object at 0x7f41e929f650>
>>> print(c.fetchall())
[('apple', 'green')]
  • 事实上,它可以是实现Sequence协议的任何对象,但是提供元组是常规的。

相关问题