2017-05-05 62 views
1

我試圖從python字典向mySql DB插入數據。但我不明白我的SQL查詢有什麼問題。pymysql.err.ProgrammingError:你的SQL語法有錯誤

我收到此錯誤:

pymysql.err.ProgrammingError: (1064, u"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''DiedIn' ('name', 'city') VALUES ('\'Ethel_Merman\'', '\'New_York_City\\n\'')' at line 1")

這是我的代碼:

import pymysql.cursors 

wasBornIn = {} 
with open("wasBornIn.txt") as f: 
for line in f: 
    (key, val) = line.split(':') 
    wasBornIn[key] = val 

diedIn = {} 
with open("diedIn.txt") as f: 
for line in f: 
    (key, val) = line.split(':') 
    diedIn[key] = val 

isLocatedIn = {} 
with open("isLocatedIn.txt") as f: 
for line in f: 
    (key, val) = line.split(':') 
    isLocatedIn[key] = val 

connection = pymysql.connect(host='********', user='******', password='******', db='*******', 
         charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor) 
try: 
with connection.cursor() as cursor: 
# Create a new record 
    sql = "DROP TABLE DiedIn" 
    cursor.execute(sql) 

with connection.cursor() as cursor: 
# Create a new record 
    sql = "DROP TABLE isLocatedIn" 
    cursor.execute(sql) 

with connection.cursor() as cursor: 
# Create a new record 
    sql = "DROP TABLE BornIn" 
    cursor.execute(sql) 

with connection.cursor() as cursor: 
    sql = "CREATE TABLE `DiedIn`(`name` varchar(100) COLLATE utf8_bin NOT NULL, `city` varchar(50) COLLATE utf8_bin NOT NULL, " \ 
     "PRIMARY KEY(`name`)) ENGINE = InnoDB DEFAULT CHARSET = utf8" \ 
      " COLLATE = utf8_bin;" 
    cursor.execute(sql) 

with connection.cursor() as cursor: 
    sql = "CREATE TABLE `isLocatedIn`(`name` varchar(150) COLLATE utf8_bin NOT NULL, `location` varchar(50) COLLATE utf8_bin NOT NULL, " \ 
     "PRIMARY KEY(`name`)) ENGINE = InnoDB DEFAULT CHARSET = utf8" \ 
      " COLLATE = utf8_bin;" 
    cursor.execute(sql) 

with connection.cursor() as cursor: 
    sql = "CREATE TABLE `BornIn`(`name` varchar(100) COLLATE utf8_bin NOT NULL, `city` varchar(50) COLLATE utf8_bin NOT NULL, " \ 
     "PRIMARY KEY(`name`)) ENGINE = InnoDB DEFAULT CHARSET = utf8" \ 
      " COLLATE = utf8_bin;" 
    cursor.execute(sql) 

with connection.cursor() as cursor: 
    for key, value in diedIn.iteritems(): 
     strKey = repr(key) 
     strValue = repr(value) 
     sql = "INSERT INTO 'DiedIn' ('name', 'city') VALUES (%s, %s);" 
     cursor.execute(sql, (strKey, strValue)) 
# connection is not autocommit by default. So you must commit to save 
# your changes. 
connection.commit() 
finally: 
connection.close() 

感謝您的幫助。

+0

( '\' Ethel_Merman \ '', '\' New_York_City \\ñ\ '')」看看那些正在創建的問題人物。逃避他們 – Exprator

回答

-1

嘗試:

sql = "INSERT INTO 'DiedIn' (name, city) VALUES ('%s', '%s');"