Python Forum
sqlite3 question - execute method with :parameter - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: sqlite3 question - execute method with :parameter (/thread-18500.html)



sqlite3 question - execute method with :parameter - richalt2 - May-20-2019

I see code using this syntax for the .execute and parameters passed with a dictionary. Where is this :parameter syntax defined?
  connection.execute("select * from :tab where :tab.fname = :firstname ",  {"tab": peopletable, "firstname": onename} )
 
I don't find this :parameter in any sqlite3 documentation? Is this dictionary string editing syntax a standard Python feature?


RE: sqlite3 question - execute method with :parameter - Yoriz - May-20-2019

https://docs.python.org/3/library/sqlite3.html#sqlite3.Cursor.execute Wrote:class sqlite3.Cursor
A Cursor instance has the following attributes and methods.

execute(sql[, parameters])
Executes an SQL statement. The SQL statement may be parameterized (i. e. placeholders instead of SQL literals). The sqlite3 module supports two kinds of placeholders: question marks (qmark style) and named placeholders (named style).

Here’s an example of both styles:
import sqlite3

con = sqlite3.connect(":memory:")
cur = con.cursor()
cur.execute("create table people (name_last, age)")

who = "Yeltsin"
age = 72

# This is the qmark style:
cur.execute("insert into people values (?, ?)", (who, age))

# And this is the named style:
cur.execute("select * from people where name_last=:who and age=:age", {"who": who, "age": age})

print(cur.fetchone())

con.close()
execute() will only execute a single SQL statement. If you try to execute more than one statement with it, it will raise a Warning. Use executescript() if you want to execute multiple SQL statements with one call.



RE: sqlite3 question - execute method with :parameter - woooee - May-20-2019

This is called named place holders http://zetcode.com/db/sqlitepythontutorial/ You can send a dictionary to a general lookup or add or delete function using named placeholders.