使用python在mysql中插入unicode值

2024-07-07 09:07:06 发布

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

我想在mysql表中插入unicode文本,为此我编写了下面的代码

我用的是烧瓶框架

import MySQLdb as ms
db = ms.connect("localhost","username","password","dbname")
cursor = db.cursor()

my_text = "का" #this is marathi lang word
enc = my_text.encode('utf-8')  #after encoding still it shows me marathi word
db_insert = "INSERT INTO TEXT(text) VALUES '{0}'"
cursor.execute(db_insert,(enc))
db.commit()

它给出了以下错误

TypeError: not all arguments converted during string formatting on line cursor.execute()

如何删除此错误?在


Tags: 代码text文本executedbmy错误mysql
2条回答

您需要将一个序列(一个listtuple)传递给paramsincursor.execute语句:

db_insert = "INSERT INTO TEXT(text) VALUES (%s)"
# notice the comma at the end to convert it to tuple
cursor.execute(db_insert,(enc,)) 

您可以在documentation中阅读更多:

Why the tuple? Because the DB API requires you to pass in any parameters as a sequence.


或者,您甚至可以使用named parameters

^{pr2}$

把这个放在源代码的开头:

# -*- coding: utf-8 -*-

不要对已经编码的内容进行编码-删除my_text.encode('utf-8')

在连接调用中使用charset="utf8", use_unicode=True。在

表/列中的CHARACTER SET必须是utf8或{}。latin1是否会使正常工作。在

Python checklist

相关问题 更多 >