如何在pymysql

时间:2018-09-18 23:28:28

标签: python sql pymysql

此代码使用pymysql,但是,当我尝试将变量标题插入sql查询时,它带有“标题”,例如,当我将title设置为= test时,创建的数据库为“ test”时,是否有创建方法没有多余引号的桌子

   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))

1 个答案:

答案 0 :(得分:1)

在我的情况下,我只是 在类'pymysql.connections.Connection'中重写了转义方法,显然在字符串周围添加了“'” 。 / em>

我不知道这是一个坏主意,但是似乎没有更好的方法,如果有人知道,那就让我知道。

这是我的代码:

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()