0

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/

2 Answers 2

0

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

Sign up to request clarification or add additional context in comments.

Comments

0

The sql_command string being generated should be something like this (Formatted string):

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

1 Comment

could you post the schema for my_table

Your Answer

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