6

I'm trying to debug a SQL statement generated with sqlite3 python module...

c.execute("SELECT * FROM %s WHERE :column = :value" % Photo.DB_TABLE_NAME, {"column": column, "value": value})

It is returning no rows when I do a fetchall()

When I run this directly on the database

SELECT * FROM photos WHERE album_id = 10

I get the expected results.

Is there a way to see the constructed query to see what the issue is?

3 Answers 3

16

To actually answer your question, you can use the set_trace_callback of the connection object to attach the print function; this will make all queries get printed when they are executed. Here is an example in action:

# Import and connect to database
import sqlite3
conn = sqlite3.connect('example.db')
# This attaches the tracer
conn.set_trace_callback(print)
# Get the cursor, execute some statement as an example
c = conn.cursor()
c.execute("CREATE TABLE stocks (symbol text)")
t = ('RHAT',)
c.execute("INSERT INTO stocks VALUES (?)", t)
c.execute('SELECT * FROM stocks WHERE symbol=?', t)
print(c.fetchone())

This produces the output:

CREATE TABLE stocks (symbol text)
BEGIN 
INSERT INTO stocks VALUES ('RHAT')
SELECT * FROM stocks WHERE symbol='RHAT'
('RHAT',)
Sign up to request clarification or add additional context in comments.

3 Comments

conn.set_trace_callback(print) is the key line here, works with sqlite3 flawlessly.
This doesn't seem to work for me. I'm still getting INSERT INTO stocks VALUES (?).
@feus4177 I concur, in Python 3.10 this seems to not display the concrete values at all, which would be the actually interesting thing.
2

the problem here is that the string values are automatically embraced with single quotes. You can not dynamically insert column names that way.

Concerning your question, I'm not sure about sqlite3, but in MySQLdb you can get the final query as something like (I am currently not at a computer to check):

statement % conn.literal(query_params)

2 Comments

That doesn't seem to work with sqlite: 'sqlite3.Connection' object has no attribute 'literal'
@RomualdBrunet, you are right. I've took a look at code.google.com/p/pysqlite/source/browse/src and can not see anything that can be user for the purpose. There is sqlite3.Statement that should have a bind_parameters method, but no methods are available in python for the class.
1

You can only use substitution parameters for row values, not column or table names.

Thus, the :column in SELECT * FROM %s WHERE :column = :value is not allowed.

Comments

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.