2013-06-11 2 views
9

파이썬 스크립트 내에서 MySQL 테이블에 파이썬 변수를 삽입하려하지만 작동하지 않습니다. 나는이 작업을 수행 실제 수치와 result[1,0], result[1,1]result[1,2] 변수 이름을 교체 할 때 여기, 내 코드MySQL 커넥터/파이썬 - 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' 

를 얻을 수있다. 나는 파이썬이 보유하고있는 값보다는 실제 변수 이름을 전달하고 있다고 생각합니다. 이 문제를 어떻게 해결할 수 있습니까?

+0

누구나? ........ – user1893354

+0

연결 = engine.connect() connection.execute ("" "플레이어가 Gold = (?)로 설정 한 경우 Name = (?)" "" 이름)), 아마 fanboy 일이지만 파이썬과 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 커넥터에서 인식 할 수 없습니다. Dict을 채우는 데 진짜 파이썬 float으로 전송하십시오.

0

당신은 파이썬 3에있는 이상, 단지 mysqlclient pip install mysqlclient를 사용하는 경우. 그것은 장고에 의해 권장되며 다른 모든 드라이버가 나쁘다.

관련 문제