Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sqlite / python - named parameters without enclosing quotes?

When using prepared statements with named parameters in SQLite (specifically with the python sqlite3 module http://docs.python.org/library/sqlite3.html ) is there anyway to include string values without getting quotes put around them ?

I've got this :

columnName = '''C1'''
cur = cur.execute('''SELECT DISTINCT(:colName) FROM T1''', {'colName': columnName})

And it seems the SQL I end up with is this :

SELECT DISTINCT('C1') FROM T1

which isn't much use of course, what I really want is :

SELECT DISTINCT(C1) FROM T1 .

Is there any way to prompt the execute method to interpret the supplied arguments in such a way that it doesn't wrap quotes around them ?

I've written a little test program to explore this fully so for what it's worth here it is :

import sys
import sqlite3
def getDatabaseConnection():
    DEFAULTDBPATH = ':memory:'

    conn = sqlite3.connect(DEFAULTDBPATH, detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES)
    conn.text_factory = str

    return conn

def initializeDBTables(conn):
    conn.execute('''
    CREATE TABLE T1(
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      C1 STRING);''')   
    cur = conn.cursor()
    cur.row_factory = sqlite3.Row  # fields by name 

    for v in ['A','A','A','B','B','C']:
        cur.execute('''INSERT INTO T1 values (NULL, ?)''', v)

    columnName = '''C1'''
    cur = cur.execute('''SELECT DISTINCT(:colName) FROM T1''', {'colName': columnName})

    #Should end up with three output rows, in
    #fact we end up with one
    for row in cur:
        print row


def main():
    conn = getDatabaseConnection()
    initializeDBTables(conn)

if __name__ == '__main__':
    main()

Would be interested to hear of anyway of manipulating the execute method to allow this to work.

like image 288
glaucon Avatar asked Oct 14 '22 21:10

glaucon


1 Answers

In SELECT DISTINCT(C1) FROM T1 the C1 is not a string value, it is a piece of SQL code. The parameters (escaped in execute) are used to insert values, not pieces of code.

like image 179
eumiro Avatar answered Nov 02 '22 22:11

eumiro