在Python中使用SQLite3选择多个​​列

时间:2015-04-16 22:24:10

标签: python database sqlite

我有一个列表,其中包含我想从数据库中的表中检索的列的名称。 我的问题是如何使光标选择列表中指定的列。在将nameList包含在select语句中之前,是否必须将nameList转换为字符串变量?感谢

nameList = ['A','B','C','D',...]

 with sqlite3.connect(db_fileName) as conn:
        cursor = conn.cursor()
        cursor.execute("""
        select * from table
        """)

2 个答案:

答案 0 :(得分:2)

只要您确定您的输入已被清理 - 以避免SQL injection攻击 - 您可以这样做:

    ...
    qry = "select {} from table;"
    qry.format( ','.join(nameList) )
    cursor.execute(qry)

如果您使用的是旧版本的Python,请改为:

    ...
    qry = "select %s from table;"
    qry % ','.join(nameList) 
    cursor.execute(qry)

答案 1 :(得分:1)

nameList = ["'A(pct)'",'B','C','D',...]

 with sqlite3.connect(db_fileName) as conn:
        cursor = conn.cursor()
        cursor.execute("""
        select {} from table
        """.format(", ".join(nameList)))
相关问题