sql = "INSERT IGNORE INTO users_time_zone (user_id, email, username, gcm_reg_id, time_zone) " \
"VALUES(%s, '%s', '%s', '%s', '%s') ON DUPLICATE KEY UPDATE gcm_reg_id ='%s', id=LAST_INSERT_ID(id) " % \
(user_data['user_id'], user_data['email'], user_data['username'],
user_data['gcm_reg_id'], user_data['time_zone'], user_data['gcm_reg_id'])
print sql
cursor = conn.cursor()
cursor.execute(sql)
conn.commit()
有时用户名就像dinda_a'yunin或者dinda_a“yunin这样会让sql像这样
INSERT IGNORE INTO users_time_zone (user_id, email, username, gcm_reg_id, time_zone) VALUES(4298849, 'dinda_a'yunin@yahoo.com', 'dinda_ayunin', 'APA91bGRvg74', 'Asia/Jakarta') ON DUPLICATE KEY UPDATE gcm_reg_id ='APA91bGRvg74', id=LAST_INSERT_ID(id)
这使得错误的语法无论如何都要解决
答案 0 :(得分:1)
您的代码容易受到SQL Injection此处...
的影响您要么使用prepared statement:
sql = "INSERT IGNORE INTO users_time_zone (user_id, email, username, gcm_reg_id, time_zone) " \
"VALUES(%s, %s, %s, %s, %s) ON DUPLICATE KEY UPDATE gcm_reg_id =%s, id=LAST_INSERT_ID(id) "
data = (user_data['user_id'], user_data['email'], user_data['username'],
user_data['gcm_reg_id'], user_data['time_zone'], user_data['gcm_reg_id'])
cursor = conn.cursor()
cursor.execute(sql, data)
data = list(conn.escape_string, data)
sql = "INSERT IGNORE INTO users_time_zone (user_id, email, username, gcm_reg_id, time_zone) " \
"VALUES(%s, '%s', '%s', '%s', '%s') ON DUPLICATE KEY UPDATE gcm_reg_id ='%s', id=LAST_INSERT_ID(id) "\
% data