由于字符串中的单引号或双引号,sql语法错误

时间:2015-05-05 07:38:40

标签: python mysql

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)

这使得错误的语法无论如何都要解决

1 个答案:

答案 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)

escape data manually

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