使用 psycopg 迭代不同的表时不会导致获取错误
我想将多个表导出到 .json 文件。首先,我查询我想要的那些表,匹配一些条件,第二个查询,构建我想要存储的 json 对象。我正在使用 psycopg2,但是当它运行时,第一项的循环会完成其工作,然后当列表中的第二项开始时,它会返回:
没有可获取的结果
try:
connection = psycopg2.connect(user...)
with connection.cursor() as cursor:
try:
cursor = connection.cursor()
cursor.execute(
"SELECT table_name FROM information_schema.views WHERE table_schema = 'public' and table_name LIKE 'text%' ORDER BY table_name ASC;")
tablenames = cursor.fetchall()
table_names_list = [row[0] for row in tablenames]
for table in table_names_list:
print(table)
query=(
" SELECT jsonb_build_object( ...) AS feature FROM ( SELECT * FROM {tb} LIMIT 10) inputs ".format(tb=table))
sql_to_file=("COPY ({0}) TO STDOUT").format(query)
rows=cursor.fetchall()
filename = "%s.json" % table
print('File: ' + filename + ' created')
with open(filename, "w") as f:
cursor.copy_expert(sql_to_file, f)
connection.commit()
except Exception as e:
connection.rollback()
print(e)
except (Exception, psycopg2.Error) as error:
print("Error while fetching data from PostgreSQL", error)
finally:
# closing database connection.
if connection:
cursor.close()
connection.close()
print("PostgreSQL connection is closed")
我尝试遵循 psypcopg2 站点中的一些说明 和其他一些 线程,但找不到有关此错误或如何解决该错误的信息。
I want to export several tables to .json file. First, I have query for those tables I want, matching some condition, the second query, build the json object that I want to store. I am using psycopg2, but when it runs, the loop for the 1st item do its job, and then when the 2nd item in the list is starting it returns:
no results to fetch
try:
connection = psycopg2.connect(user...)
with connection.cursor() as cursor:
try:
cursor = connection.cursor()
cursor.execute(
"SELECT table_name FROM information_schema.views WHERE table_schema = 'public' and table_name LIKE 'text%' ORDER BY table_name ASC;")
tablenames = cursor.fetchall()
table_names_list = [row[0] for row in tablenames]
for table in table_names_list:
print(table)
query=(
" SELECT jsonb_build_object( ...) AS feature FROM ( SELECT * FROM {tb} LIMIT 10) inputs ".format(tb=table))
sql_to_file=("COPY ({0}) TO STDOUT").format(query)
rows=cursor.fetchall()
filename = "%s.json" % table
print('File: ' + filename + ' created')
with open(filename, "w") as f:
cursor.copy_expert(sql_to_file, f)
connection.commit()
except Exception as e:
connection.rollback()
print(e)
except (Exception, psycopg2.Error) as error:
print("Error while fetching data from PostgreSQL", error)
finally:
# closing database connection.
if connection:
cursor.close()
connection.close()
print("PostgreSQL connection is closed")
I have tried to follow some instruction in the psypcopg2 site and some other threads, but cannot find information regarding this error or how to solve it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论