簡體   English   中英

MySQL Connector / Python - 將python變量插入MySQL表

[英]MySQL Connector/Python - insert python variable to MySQL table

我正在嘗試將python變量插入到python腳本中的MySQL表中,但它無法正常工作。 這是我的代碼

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

這會得到錯誤

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

但是,當我將變量名稱result[1,0]result[1,1]result[1,2]替換為它們的實際數值時,它確實有效。 我懷疑python傳遞的是實際的變量名而不是它們持有的值。 我該如何解決?

假設您使用的是mysql.connector (我認為您是),請定義您自己的轉換器類:

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)

您傳遞的值之一可能是numpy.float64類型,MySQL連接器無法識別它。 在填充字典時將它投射到真正的python float

如果你在python 3及以上,只需使用mysqlclient pip install mysqlclient 這是django推薦的,所有其他驅動程序都不好。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM