简体   繁体   中英

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.

I tried to leave tbname outside the ending quotation mark, hoping that in this way Python knows tbname is a variable. 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,))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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