Python psycopg2不在utf-8中

时间:2022-04-19 20:20:33

I use Python to connect to my postgresql data base like this:

我使用Python连接到我的postgresql数据库,如下所示:

conn=psycopg2.connect(database="fedour", user="fedpur", password="***", host="127.0.0.1", port="5432")

No problem for that.

没有问题。

But when I make a query and I want to print the cursor I have something like this:

但当我进行查询并打印光标时,我有如下内容:

"Fran\xc3\xa7ois" instead of "François" and it cause problem when I want to create a XML document with this. I thkink is come from my encodage, but I found any solution. I try to encode('utf-8') but doesn't work.

“Fran\xc3\xa7ois”而不是“Francois”,当我想用这个创建一个XML文档时,它会导致问题。4 .我是初来乍到,但还未找到解决方案。我试着去编码(utf-8),但是不管用。

I have also seen something like this, but its only for mySQL

我也见过类似的东西,但仅限于mySQL

MySQLdb.connect(charset='utf8', init_command='SET NAMES UTF8')

Can you help me ? Thanks

你能帮我吗?谢谢

2 个解决方案

#1


4  

Make sure you're using the right encodind by running: print conn.encoding, and if you need, you can set the right encoding by conn.set_client_encoding('UNICODE'), or conn.set_client_encoding('UTF8').

确保您使用的是正确的encodind: print conn.encoding,如果您需要,您可以通过conn.set_client_encoding('UNICODE')或conn.set_client_encoding('UTF8')来设置正确的编码。

#2


0  

Does the value get inserted correctly when query is executed via command prompt?

当通过命令提示执行查询时,是否正确插入值?

If yes, then the problem is with your cursor execution.Try cur.execute(u"querystring");(The u indicates utf encoding)

如果是,那么问题是您的光标执行。尝试使用cur.execute(u“querystring”);(u表示utf编码)

If no, then you need to set the encoding type of postgres to consider utf-8. You can refer character encoding in Postgres to see how to set default character encoding for a database, and on-the-fly conversion from one encoding to another.

如果没有,那么您需要设置postgres的编码类型以考虑utf-8。您可以在Postgres中引用字符编码,查看如何设置数据库的默认字符编码,以及如何从一个编码转换到另一个编码。

#1


4  

Make sure you're using the right encodind by running: print conn.encoding, and if you need, you can set the right encoding by conn.set_client_encoding('UNICODE'), or conn.set_client_encoding('UTF8').

确保您使用的是正确的encodind: print conn.encoding,如果您需要,您可以通过conn.set_client_encoding('UNICODE')或conn.set_client_encoding('UTF8')来设置正确的编码。

#2


0  

Does the value get inserted correctly when query is executed via command prompt?

当通过命令提示执行查询时,是否正确插入值?

If yes, then the problem is with your cursor execution.Try cur.execute(u"querystring");(The u indicates utf encoding)

如果是,那么问题是您的光标执行。尝试使用cur.execute(u“querystring”);(u表示utf编码)

If no, then you need to set the encoding type of postgres to consider utf-8. You can refer character encoding in Postgres to see how to set default character encoding for a database, and on-the-fly conversion from one encoding to another.

如果没有,那么您需要设置postgres的编码类型以考虑utf-8。您可以在Postgres中引用字符编码,查看如何设置数据库的默认字符编码,以及如何从一个编码转换到另一个编码。