(Python MySQLdb)尝试将UTF8插入MySQL时

2024-07-08 14:46:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我找不到解决办法。 你能帮我回答这个问题吗?在

    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')

错误是:


Tags: dbsqlusernameuseridddbuserdicnation
1条回答
网友
1楼 · 发布于 2024-07-08 14:46:33

您需要使用参数化查询:

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

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

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

相关问题 更多 >

    热门问题