How to do parametrized queries using pypyodbc in Python? -
i'm discovering python , stuck @ error don't understand.
when querying sql server database parameters, understood examples, way is:
import pypyodbc connectionstring = 'driver={sql server};server=vsql001;database=tests;trusted_connection=yes' connection = pypyodbc.connect(connectionstring) cursor = connection.cursor() cursor.execute('select 1 ? = ?', [1, 2]); cursor.close() connection.close()
as execute following code, receive following error:
traceback (most recent call last):
file "c:\program files (x86)\python\lib\site-packages\pypyodbc.py", line 1171, in prepare
check_success(self, ret)
file "c:\program files (x86)\python\lib\site-packages\pypyodbc.py", line 937, in check_success
ctrl_err(sql_handle_stmt, odbc_obj.stmt_h, ret, odbc_obj.ansi)
file "c:\program files (x86)\python\lib\site-packages\pypyodbc.py", line 919, in ctrl_err
raise databaseerror(state,err_text)
pypyodbc.databaseerror: ('07009', '[07009] [microsoft][odbc sql server driver]invalid descriptor index')during handling of above exception, exception occurred:
traceback (most recent call last):
file "\mframe\data\profiles\arsene\desktop\query.py", line 7, in
cursor.execute('select 1 ? = ?', ['1', '2']);
file "c:\program files (x86)\python\lib\site-packages\pypyodbc.py", line 1398, in execute
self.prepare(query_string)
file "c:\program files (x86)\python\lib\site-packages\pypyodbc.py", line 1174, in prepare
if sys.exc_info()[1][0] == '07009':
typeerror: 'databaseerror' object not support indexing
what doesn't support indexing? how should write execute
statement correctly?
i've played bit , think there must bug in pypyodbc make not behave documentation suggests:
in cases, can try pypyodbc in existing pyodbc powered script following changes
for example, ran code pyodbc
, works fine:
... import pyodbc db ... conn = db.connect(connect_string) ... cursor = conn.cursor() >>> # 1 parameter ... res = cursor.execute("select 1 1=?", [1,]) ... print(cursor.fetchall()) [(1, )] >>> # 2 parameters ... res = cursor.execute("select 2 ?=?", [1, 1]) ... print(cursor.fetchall()) [(2, )] >>> conn.close()
but switching import line pypyodbc
breaks second example:
... import pypyodbc db ... conn = db.connect(connect_string) ... cursor = conn.cursor() >>> # 1 parameter ... res = cursor.execute("select 1 1=?", [1,]) ... print(cursor.fetchall()) [(1,)] >>> # 2 parameters ... res = cursor.execute("select 2 ?=?", [1, 1]) ... print(cursor.fetchall()) traceback (most recent call last): ... typeerror: 'databaseerror' object not support indexing >>> conn.close()
so don't think you're doing wrong; either pypyodbc broken use case or documentation wrong. if can figure out i'll file bug.
Comments
Post a Comment