1

I have a list that contains the name of columns I want to retrieve from a table in the database. My question is how to make the cursor select columns specified in the list. Do I have to convert nameList to a string variable before include it in the select statement? Thanks

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

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

2 Answers 2

2

As long as you can be sure your input is sanitized -- to avoid SQL injection attack -- you can do:

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

If you're on a really old version of Python do instead:

    ...
    qry = "select %s from table;"
    qry % ','.join(nameList) 
    cursor.execute(qry)
Sign up to request clarification or add additional context in comments.

3 Comments

Good warning against SQL injection. That still isn't second nature to me coming from an Access background.
qry = "select {} from table;" qry.format( ','.join(nameList) ), it seems Python does not accept since string is immutable and can't be changed? Could you double check? Error message is unrecognized token: "{" . Thanks
@bernie: There is still some problem with the updated solution. Nivix's solution seems to be working
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)))

5 Comments

what if nameList contains column names like this, 'A(pct)', 'B(pct)'. This will break down your code since Python thought you might be calling some function with parameter pct. Thanks
Python doesn't think you are calling a function, it just handles strings as strings. But the SQL might think A(pct) is a SQL function..so you might need to put single quotes around those column names. See this: stackoverflow.com/a/25210041/4774955
In SQL, single quotes are for strings, and double quotes are for table/column names.
@CL Depends on which database software you are using. Single quotes are valid in MSSQL.
That's why I said "SQL", and did not mention a certain database that does not conform to the SQL standard.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.