【问题标题】:(Python MySQLdb) when trying to insert UTF-8 into MySQL(Python MySQLdb) 尝试将 UTF-8 插入 MySQL 时
【发布时间】:2012-11-13 08:04:02
【问题描述】:

我找不到解决方案。 你能帮我解决这个问题吗?

    dic={'username':u'\uc774\ud55c\ub098','userid':u'david007', 'nation':u'\ub300\ud55c\ubbfc\uad6d'}
    c=MySQLdb.connect(host=ddb['host'],user=ddb['user'],passwd=ddb['passwd'],db=ddb['db'], use_unicode=True, charset="utf8")
    s=c.cursor()
    sql="INSERT INTO "+db+" "+col+" VALUES "+str(tuple(dic.values()))
    s.execute(sql)

    "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 ''\\uc774\\ud55 ... at line 1")

    print sql
    INSERT INTO user_tb (username, userid, nation) VALUES (u'\uc774\ud55c\ub098', u'david007', u'\ub300\ud55c\ubbfc\uad6d')

错误是:

【问题讨论】:

  • 那甚至不是有效的 Python 代码。您可以按照代码中的说明包含光标.execute() 调用吗?看起来你在那里混合了你的 python 字符串文字语法,但我想看看这是细节。
  • 可能在值中添加单引号

标签: python mysql utf-8


【解决方案1】:

您需要使用参数化查询:

sql = "INSERT INTO " + db + " " + col + " VALUES (%s, %s, %s)"
s.execute(sql, dic.values())

当您简单地将元组连接到查询时,unicode 字符串的 u 前缀将使这些字符串无效 SQL。使用参数 MySQLdb,将通过参数替换做正确的事情(即将 unicode 字符串编码为字节表示)并生成有效的 SQL。

作为一般原则,您应该始终在查询中使用参数来防止 SQL 注入。

【讨论】:

  • user1161599@ 您确实将u'\uc774\ud55c\ub098' 等Python 转义代码放入SQL 中,但数据库不了解Python 类型的转义和u 前缀。请注意,“Perdo”正确地根本不使用将字符串解析为 SQL 字符串,因为它容易受到 SQL 注入攻击。他使用参数。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-05-11
  • 2012-06-13
  • 2013-09-01
  • 1970-01-01
  • 2013-05-05
  • 2017-05-14
  • 1970-01-01
相关资源
最近更新 更多