简体   繁体   中英

retrieving data from table based on a value from a python variable

I am writing a function that will retrieve data from sqlite table based on the parameters user provide. This is the function so far

def database_retrieve(db_file, id):
    try:
        conn = sqlite3.connect(db_file)

        with conn:
            sql_command = "SELECT * FROM my_table WHERE id = "+id

            cur = conn.cursor()
            cur.execute(sql_command)
            result = cur.fetchall()

            return result

    except Exception as e:
        print(e)

db_file = 'testdb.db'
print(database_retrieve(db_file, 'subject1'))

This gives me the following error

no such column: subject1
None

When I add subject1 , which is an entry under the id column in my_table , directly to the sql command like this

sql_command = "SELECT * FROM my_table WHERE id = 'subject1'"

it works fine and prints all the data.

I am new to sqlite3. Please help. Thanks in advance

These are the links I used to come this far Python sqlite3 string variable in execute

https://www.dummies.com/programming/databases/how-to-retrieve-data-from-specific-rows-in-mysql-databases/

When you do this

sql_command = "SELECT * FROM my_table WHERE id = "+id

The value of sql_command is

"SELECT * FROM my_table WHERE id = subject1"

As you can see, subject1 is not in quotes. sqlite thinks it is a column, that's why you see that error.

Instead, do this

sql_command = "SELECT * FROM my_table WHERE id = ?"
cur.execute(sql_command, [id])

? acts as a placeholder for the variable id .

The official sqlite3 documentation mentions few others methods https://docs.python.org/2/library/sqlite3.html

生成的sql_command字符串应类似于以下内容(格式化字符串):

sql_command = "SELECT * FROM my_table WHERE id = %s AND name = %s" % (212212, 'shashank')

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