我有一个脚本,该脚本从一个数据库中获取数据,并根据表的名称和字段将其复制到另一个数据库中。 问题是关于unicode数据,我需要在俄语中插入一些单词,但是每次psycopg2像默认字符串一样写入它时。
import psycopg2
import psycopg2.extensions
conn_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中结果的样子:
我也尝试设置extins并以unicode插入数据,但是在这种情况下我出错了
import psycopg2
import psycopg2.extensions
psycopg2.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 exist
LINE 1: ...ing_ex" ("num", "name", "district") VALUES (23, u'\u0420\u...
^
在这里应该做什么?
答案 0 :(得分:1)
不要使用烘烤的值来准备您的字符串(使用字符串格式或串联)。
相反,请将您的值作为参数传递给.execute
方法。
例如
sql = 'INSERT INTO {} ({}) VALUES (%s, %s, %s);'.format('"tb_names"', '"num", "name", "district"')
cur_2.execute(sql, (23, u'Рынок', u'Волжский'))