MySQL Connector/Python - insert python variable to MySQL table

后端 未结 3 1760
旧巷少年郎
旧巷少年郎 2020-12-16 03:11

I\'m trying to insert a python variable into a MySQL table within a python script but it is not working. Here is my code

add_results=(\"INSERT INTO account_         


        
相关标签:
3条回答
  • 2020-12-16 03:28

    If you are on python 3 and above, just use mysqlclient pip install mysqlclient. It is recommended by django and all the other drivers are bad.

    0 讨论(0)
  • 2020-12-16 03:30

    Assuming you are using mysql.connector (I think you are), define your own converter class:

    class NumpyMySQLConverter(mysql.connector.conversion.MySQLConverter):
        """ A mysql.connector Converter that handles Numpy types """
    
        def _float32_to_mysql(self, value):
            return float(value)
    
        def _float64_to_mysql(self, value):
            return float(value)
    
        def _int32_to_mysql(self, value):
            return int(value)
    
        def _int64_to_mysql(self, value):
            return int(value)
    
    config = {
        'user'    : 'user',
        'host'    : 'localhost',
        'password': 'xxx',
        'database': 'db1'
    }
    
    conn = mysql.connector.connect(**config)
    conn.set_converter_class(NumpyMySQLConverter)
    
    0 讨论(0)
  • 2020-12-16 03:46

    One of your passed values could be of type numpy.float64 which is not recognized by the MySQL connector. Cast it to a genuine python float on populating the dict.

    0 讨论(0)
提交回复
热议问题