How to see the real SQL query in Python cursor.execute using pyodbc and MS-Access

前端 未结 9 1389
有刺的猬
有刺的猬 2020-12-04 17:17

I use the following code in Python (with pyodbc for a MS-Access base).

cursor.execute(\"select a from tbl where b=? and c=?\", (x, y))

It\'

相关标签:
9条回答
  • 2020-12-04 18:12

    I'd check cursor._last_executed afterwards, but if you want them printed out in real time without changing every execute try this monkey patch:

    def log_queries(cur):
        def _query(q):
            print q # could also use logging
            return cur._do_query(q)
        cur._query = _query
    
    conn = MySQLdb.connect( read_default_file='~/.my.cnf' )
    cur = conn.cursor()
    log_queries(cur)
    cur.execute('SELECT %s, %s, %s', ('hello','there','world'))
    

    It's very dependent on MySQLdb (and could break in later versions). It works because cur._query currently simply calls calls._do_query and returns its result.

    0 讨论(0)
  • 2020-12-04 18:13

    Write the sql string and then execute it:

    sql='''select a 
           from tbl 
           where b=? 
           and c=? '''
    
    cursor.execute(sql, x, y)
    print 'just executed:',(sql, x,y)
    

    Now you can do whatever you want with the SQL statement.

    0 讨论(0)
  • 2020-12-04 18:20

    Since pyodbc doesn't have a way to see the query BEFORE it is executed. You can pre-populate the query manually just to get an idea of what it will end up looking like. It's not going to work as the actual query, but it helped me figure out if I had any errors in a query that needed more than 40 parameters.

    query = """select * from [table_name] where a = ? and b = ?"""
    
    parameter_list = ['dog', 'cat'] # List of parameters, a = 'dog', b = 'cat'.
    
    query_list = list(query) # Split query string into individual characters.
    
    # Loop through list and populate the question marks.
    for i in range(len(parameter_list)):
        for idx, val in enumerate(query_list):
            if val == '?':
                query_list[idx] = str(parameter_list[i])
                break
    
    # Rejoin the query string.
    query_populate = ''.join(query_list)
    
    #### Result ####
    """select * from [table_name] where a = dog and b = cat"""
    
    0 讨论(0)
提交回复
热议问题