如何删除多余的pymysql报价(How to remove extra quotes in pym

2019-10-29 03:00发布

此代码使用pymysql,但是当我尝试插入变量标题到SQL查询它出来有例如“标题”当我设置标题=测试创建的数据库是“测试”是有办法创建该表额外的报价

   import pymysql
    connection = pymysql.connect(
        host='localhost',
        user='root',
        password='',
        db='comments',
    )
    c= connection.cursor()
    sql ='''CREATE TABLE IF NOT EXISTS `%s` (
      `comment_id` int(11) NOT NULL,
      `parent_comment_id` int(11) NOT NULL,
      `comment` varchar(200) NOT NULL,
      `comment_sender_name` varchar(40) NOT NULL,
      `date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8; '''
    c.execute(sql, (title))

Answer 1:

在我来说,我只是重写类的pymysql.connections.Connection“,这显然增加了“'”你的角落找寻字符串中逃生方法

我不知道它是否是一个坏主意,但似乎没有更好的办法,如果有人知道,只是让我知道。

这里是我的代码:

from pymysql.connections import Connection, converters


class MyConnect(Connection):
    def escape(self, obj, mapping=None):
        """Escape whatever value you pass to it.

        Non-standard, for internal use; do not use this in your applications.
        """
        if isinstance(obj, str):
            return self.escape_string(obj)  # by default, it is :return "'" + self.escape_string(obj) + "'"
        if isinstance(obj, (bytes, bytearray)):
            ret = self._quote_bytes(obj)
            if self._binary_prefix:
                ret = "_binary" + ret
            return ret
        return converters.escape_item(obj, self.charset, mapping=mapping)


config = {'host':'', 'user':'', ...}
conn = MyConnect(**config)
cur = conn.cursor()


文章来源: How to remove extra quotes in pymysql