以任何方式使用pyodbc返回文字SQL

时间:2013-10-01 21:54:25

标签: python sql-server python-2.7 pyodbc

有没有办法使用pyodbc返回传递给数据库的文字sql?我将参数传递给for循环中的语句迭代字典列表。例如:

mylist = [{'name': 'john', 'key': 1}, {'name': 'jane', 'key': 2}]
sql = "update people set name = ? where key = ?"
for i in mylist:
    cursor.execute(sql, i['name'], i['key']) 

我希望能够打印或存储脚本传递给数据库的文字sql。如果使用pyodbc无法做到这一点,有人可以推荐一个具有此功能的不同Python模块吗?提前致谢。

2 个答案:

答案 0 :(得分:1)

它不是内置的,但实现起来相当简单。

与其他解决方案类似。但写一个通用的方法,如:

def executeAndLog( db_cursor, sql, *args ) :
    run_sql = sql.replace( '?', '{!r}' ).format( *args )
    try:
        db_cursor.execute( sql, *args )
        logging.info( run_sql )
    except Exception as e:
        logging.error( " ".join( run_sql, "failed with error", e ) )

您可能需要向调用者说明是否成功,因此要么返回一些内容,要么重新引发异常。

答案 1 :(得分:0)

您可以使用内置日志记录模块:

import logging
import pyodbc

# setup logging level and file name
logging.basicConfig(filename='sql.log', level=logging.DEBUG)

# connection = pyodbc....
# cursor = connection...

# define parameter values and sql 
mylist = [{'name': 'john', 'key': 1}, {'name': 'jane', 'key': 2}]
sql = "update people set name = ? where key = ?"

for i in mylist:
    cursor.execute(sql, i['name'], i['key'])
    # {!r} ensures string values wrapped with single quote
    logging.debug(sql.replace('?', '{!r}').format(i['name'], i['key']))

您可能希望在cursor.execute周围添加一些异常处理,以便仅在呼叫成功时进行记录。