2013-04-22 5 views
0

줄 단위로 파일의 데이터를 읽고 MySQL 데이터베이스에 각 행을 삽입하는 스크립트를 작성하고 있습니다. 나는 이것을하기 위해 mysql.connector를 사용한다. 다음은 스크립트입니다.Python에서 테이블에 데이터를 삽입 할 때 mysql.connector.ProgrammingError

def insert_query(data): 
    return ("INSERT INTO " + tblname + " (`log`) " + "VALUES " + "(" + "'" + data + "'" + ")") 
with open('data.txt', 'r') as f: 
    lines = f.readlines() 

for line in lines: 
    add_line = insert_query(line) 
    cursor.execute(add_line) 
    cursor.commit() 

파일 data.txt의 크기는 5Mbyte이지만 약 10000 개의 행이 있습니다. tblname에는 2 개의 필드가 있습니다. ID - INT (11) (자동 증가), 로그 - 텍스트 이 스크립트를 실행하면 데이터베이스에 약 100 줄이 추가되고 충돌합니다.

mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for ')'

MySQL 버전 : 5.5.27 어떻게이 문제를 해결하기 그것은 오류를보고? 감사.

답변

0

삽입 문이 잘못되었습니다. 'tblname'이 (가) 함수에서 정의되지 않았으므로 구문 오류가 발생합니다. 그러나 문제를 해결하는 데있어 더 큰 문제가 있습니다. 로그의 한 줄에 따옴표와 대괄호가 있으면 어떻게합니까?

파일에서 데이터를 읽고 라인으로 라인을 삽입하는 방법 다음 코드 쇼 : 빠를 것이다,

stmt = "INSERT INTO {table} (c1) VALUES (%s)".format(table=table_name) 

with open('data.txt', 'r') as fp: 
    for line in fp: 
     data = (line.strip(),) 
     cur.execute(stmt, (line.strip(),)) 
cnx.commit() 

또는 사용 executemany() :

with open('data.txt', 'r') as fp: 
    cur.executemany(stmt, [(line.strip(),) for line in fp]) 
cnx.commit() 
관련 문제