Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL Connector/Python - insert python variable to MySQL table

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_cancel_predictions"
            "(account_id,21_day_probability,flagged)"
            "Values(%(account_id)s,%(21_day_probability)s,%(flagged)s)")

data_result={
    'account_id':result[1,0],
    '21_day_probability':result[1,1],
    'flagged':result[1,2]
}

cursor.execute(add_results,data_result)

cnx.commit()
cursor.close()
cnx.close()

This gets the error

ProgrammingError: Failed processing pyformat-parameters; 'MySQLConverter' object has no attribute '_float64_to_mysql'

However, when I replace the variable names result[1,0], result[1,1], and result[1,2] with their actual numerical values it does work. I suspect python is passing the actual variable names rather than the values they hold. How do I fix this?

like image 927
user1893354 Avatar asked Jun 11 '13 20:06

user1893354


People also ask

What is S in Python MySQL?

Use Python Variables in a MySQL Insert Query We can insert Python variables into the table using the prepared statement and parameterized query. Using a parameterized query, we can pass Python variables as a query parameter in which placeholders (%s) used for parameters.

What are the different parameters in connect () function of MySQL Connector?

connect() supports the following arguments: host , user , password , database , port , unix_socket , client_flags , ssl_ca , ssl_cert , ssl_key , ssl_verify_cert , compress .


2 Answers

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.

like image 157
Thomas Grill Avatar answered Oct 07 '22 12:10

Thomas Grill


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)
like image 43
mtrbean Avatar answered Oct 07 '22 13:10

mtrbean