简体   繁体   English

Python sqlite3,在execute语句中引用变量

[英]Python sqlite3, refer to a variable in execute statement

I'm trying to use sqlite3.connect.cursor.execute in Python to manipulate database, but not sure how to correctly construct the SELECT statement so that the tbname in the code below can be properly read in as a variable. 我正在尝试在Python中使用sqlite3.connect.cursor.execute来操作数据库,但不确定如何正确构造SELECT语句,以便可以将下面代码中的tbname正确地读入为变量。

I tried to leave tbname outside the ending quotation mark, hoping that in this way Python knows tbname is a variable. 我试图将tbname保留在引号之外,希望Python这样知道tbname是一个变量。 However the code doesn't work. 但是代码不起作用。 Any idea? 任何想法?

def print_col(dbname, tbname):
    conn = sqlite3.connect(dbname)
    c = conn.cursor()
    c.execute('SELECT sql FROM sqlite_master WHERE type = \'table\' AND tbl_name = '+ tbname)
    print c.fetchall()
    conn.close()

这是用于以下目的的参数:

c.execute("SELECT sql FROM sqlite_master WHERE type = 'table' AND tbl_name = ?", (tbname,))

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

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