Search code examples
pythonsqlpymysql

How to remove extra quotes in pymysql


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

Solution

  • 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.

    Here's my code:

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