【发布时间】:2022-06-16 22:33:48
【问题描述】:
我是数据库操作的新手,我正在编写一个 python 脚本来备份和恢复 postgres 中数据库的备份
下面是我的python脚本
import subprocess
import psycopg2
user = "postgres"
password = "postgres"
host = "localhost"
port = "5432"
database_name = "test"
dest_file = "/home/admin/temp/db.sql"
#Taking db backup
process = subprocess.Popen(['pg_dump','--dbname=postgresql://{}:{}@{}:{}/{}'.format(user, password, host, port, database_name),'-Fc','-f', dest_file],stdout=subprocess.PIPE)
output = process.communicate()[0]
if process.returncode != 0:
print('Command failed. Return code : {}'.format(process.returncode))
exit(1)
print(str(process))
#Doing db changes
#Restoring db in a chance of error
conn = psycopg2.connect(user = user,password = password,host = host,port = port)
conn.autocommit = True
with conn.cursor() as cursor:
cursor.execute('DROP DATABASE test;')
cursor.execute('CREATE DATABASE test;')
process = subprocess.Popen(['pg_restore', '--no-owner','--dbname=postgresql://{}:{}@{}:{}/{}'.format(user, password, host, port, database_name), dest_file],stdout=subprocess.PIPE)
output = process.communicate()[0]
if process.returncode != 0:
print('Command failed. Return code : {}'.format(process.returncode))
exit(1)
print(output)
执行代码时出现以下错误..
psycopg2.errors.ObjectInUse: database "test" is being accessed by other users
不知道怎么了。。 请帮忙
【问题讨论】:
-
你需要关闭连接 - conn.close() 已经回答here
标签: python database postgresql