【问题标题】:String of cursor.execute without executingcursor.execute 的字符串而不执行
【发布时间】:2020-08-17 12:11:38
【问题描述】:

我正在使用以下方法使用pymysql 对 SQL+args 查询进行参数化,但不执行它(至少合法):

try:
    self.cursor.execute(self.sql + ' ***', self.sql_args or tuple())    
except pymysql.err.ProgrammingError:                                      
    self._sql_formatted = self.cursor._last_executed.rstrip('* ')

实际上有没有pymysql 有一种方法,它只是格式化SQL 字符串而不执行它,还是我需要使用类似上面的方法?或者,另一种选择:

self.cursor.execute('DESCRIBE ' + self.sql, self.sql_args or tuple())
self._sql_formatted = self.cursor._last_executed.replace('DESCRIBE ', '')

【问题讨论】:

    标签: python mysql sql pymysql


    【解决方案1】:

    cursor.mogrify 方法

    返回通过调用 execute() 方法发送到数据库的确切字符串。

    >>> conn = pymysql.connect(host='localhost', user='root', password='password', database='test')
    >>> cur = conn.cursor()
    >>> stmt1 = """SELECT id, password FROM my_user WHERE name = %s;"""
    >>> print(cur.mogrify(stmt1, ('Alice',)))
    SELECT id, password FROM my_user WHERE name = 'Alice';
    

    【讨论】:

    • 我猜它是“transmogrify”的反向构词,它是一个 [jocular] 词,意思是“变换”。
    猜你喜欢
    • 1970-01-01
    • 2016-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-23
    • 1970-01-01
    • 2023-03-28
    • 2023-03-13
    相关资源
    最近更新 更多