如何删除pymysql中的多余引号 [英] How to remove extra quotes in pymysql

查看:48
本文介绍了如何删除pymysql中的多余引号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码使用 pymysql,但是当我尝试将变量 title 插入 sql 查询时,它会出现title",例如,当我将 title 设置为 = test 所创建的数据库是test"时,有没有办法创建没有额外引号的表格

This code uses pymysql, however when i try to insert the variable title into the sql query it comes out with 'title' for example when i set title to = test the database created is 'test' is there a way to create the table without the extra quotes

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

推荐答案

就我而言,我只是重写类 'pymysql.connections.Connection' 中的转义方法,这显然在您的周围添加了'"字符串.

In my case I just rewrite the escape method in class 'pymysql.connections.Connection', which obviously adds "'" arround your string.

我不知道这是不是一个坏主意,但似乎没有更好的方法,如果有人知道,请告诉我.

I don't know whether it is a bad idea, but there seems no better ways, if anyone knows, just let me know.

这是我的代码:

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

这篇关于如何删除pymysql中的多余引号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆