2013-06-11 66 views
9

我試圖插入python變量到python腳本內的MySQL表,但它不工作。這裏是我的代碼MySQL連接器/ 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是傳遞實際的變量名稱而不是它們所持有的值。我該如何解決?

+0

任何人?........ – user1893354

+0

connection = engine.connect() connection.execute(「」「更新玩家設置Gold =(?)其中Name =(?)」「」,(gold,名字)),也許只是一個fanboy的東西,但我傾向於使用python的sqlalchemy,這往往會簡化大部分這一點,我從來沒有使用通配符的問題 – theBigChalk

回答

18

假設你正在使用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) 
+1

好的解決方案!但是,我必須包含一個'__init__'函數才能工作。這可能是因爲我的版本。我在'conversion.py'中使用了類似於原來'MySQLConverter'類的東西。 – regeirk

3

您傳遞的值中的一個值可能是numpy.float64,它不能被MySQL連接器識別。在填充字典時將其轉換爲真正的python float

0

如果你是蟒蛇3及以上,只要使用的mysql pip install mysqlclient。它由django推薦,所有其他驅動程序都不好。