[python] sqlite3 a dotazy z promenne

Tomas Pelka tompelka na gmail.com
Středa Červen 25 16:35:18 CEST 2008


Zdravim konferenci,

narazil sem na problem vkladani databazovych dotazu z promenne, resp.
parametru. Popisi situaci, mam tridu dejme tomu data:

****************************************************
import sqlite3

class Data:
	def __init__(self,query):
		self.query = query
		self.conn = sqlite3.connect('db.db')
		self.c = self.conn.cursor()
		self.c.execute('%s' % self.query);

	def getRow(self):
		return self.c.fetchone()
*****************************************************


Chtel bych ji jako parametr zadavat cely databazovy dotaz (Pokud je to
spatne cesta poradte jak na to prosim.).

Pouziji-li teoreticky nebezpecnou metodu s retezcem (%s) dostavam tohle:
****************************************************
>>> import data
>>> d = data.Data("SELECT * FROM main_t;")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "data.py", line 10, in __init__
    self.c.execute('%s' % self.query);
sqlite3.OperationalError: near "SELECT": syntax error
****************************************************


Pouziji-li dle dokumentace bezpecnou metodu (self.c.execute('?',
(self.query));) dostavam tohle:
****************************************************
>>> import data
>>> d = data.Data("SELECT * FROM main_t;")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "data.py", line 10, in __init__
    self.c.execute('?', (self.query));
sqlite3.OperationalError: near "?": syntax error
****************************************************

Dekuji za rady, hezky den vsem.

-- 

S pozdravem Tomáš Pelka
e-mail: tompelka na gmail.com



Další informace o konferenci Python