本文介绍了psycopg2不插入Unicode数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我有一个脚本,该脚本从一个数据库中获取数据,并根据表的名称和字段将其复制到另一个数据库中。 问题是关于unicode数据,我需要在俄语中插入一些单词,但是每次psycopg2像默认字符串一样写入它时。I have a script that takes data from one database and according to tables' names and fields copies it into another database.The issue is about unicode data, I need to insert some words in Russian but every time psycopg2 writes it as if it were default string.import psycopg2import psycopg2.extensionsconn_two = psycopg2.connect(user="postgres", password="password", host = "localhost", port= "5432", dbname = "base2")cur_2 = conn_two.cursor()sql = 'INSERT INTO {} ({}) VALUES {};'.format('"tb_names"', '"num", "name", "district"', (23, 'Рынок', 'Волжский'))cur_2.execute(sql)conn_two.commit()这是pgAdmin4中的结果:Here is how the result looks like in pgAdmin4:我也尝试设置teins并在unicode中插入数据,但是在这种情况下我出错了I also tried to set exteinsions and insert data in unicode, but in this case I have an errorimport psycopg2import psycopg2.extensionspsycopg2.extensions.register_type(psycopg2.extensions.UNICODE)psycopg2.extensions.register_type(psycopg2.extensions.UNICODEARRAY)conn_two = psycopg2.connect(user="postgres", password="password", host = "localhost", port= "5432", dbname = "base2")conn_two.set_client_encoding("utf-8")conn_two.set_client_encoding('UNICODE')cur_2 = conn_two.cursor()sql = 'INSERT INTO {} ({}) VALUES {};'.format('"tb_names"', '"num", "name", "district"', (23, u'Рынок', u'Волжский'))cur_2.execute(sql)conn_two.commit()Traceback (most recent call last): File "D:\_Scripts\pgadmin.py", line <>, in <module> cur_2.execute(sql)psycopg2.ProgrammingError: ОШИБКА: тип "u" не существует # - says that type "u" does not existLINE 1: ...ing_ex" ("num", "name", "district") VALUES (23, u'\u0420\u... ^在这里应该做什么?推荐答案不要用值传入(使用字符串格式或串联)。Don't prepare your string with the values baked in (using string formatting or concatenation).相反,请将您的值传递给 .execute 方法,如下所示:Instead, pass your values to the .execute method as an argument.例如,sql = 'INSERT INTO {} ({}) VALUES (%s, %s, %s);'.format('"tb_names"', '"num", "name", "district"')cur_2.execute(sql, (23, u'Рынок', u'Волжский')) 这篇关于psycopg2不插入Unicode数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 09-12 09:39