使用Python连接到PSQL数据库
请看下面使用Python在PSQL中创建表的命令。connection.close()之后是否有任何命令可以打开连接或再次获取到数据库的连接,这样我们就不需要编写整个命令来获取连接,并且可以轻松地更改创建的表中的数据使用Python连接到PSQL数据库,python,database-connection,psql,Python,Database Connection,Psql,请看下面使用Python在PSQL中创建表的命令。connection.close()之后是否有任何命令可以打开连接或再次获取到数据库的连接,这样我们就不需要编写整个命令来获取连接,并且可以轻松地更改创建的表中的数据 import psycopg2 try: connection = psycopg2.connect(database = "staff", user = "XYZ", password = "python",
import psycopg2
try:
connection = psycopg2.connect(database = "staff", user = "XYZ", password = "python", host = "localhost", port = "5432")
except psycopg2.Error as err:
print("An error was generated!")
else:
print("Connection to database was successful!")
cursor = connection.cursor()
cursor.execute('''create table mystaff.employees
(id int primary key not null,
first_name varchar(25) not null,
last_name varchar(25) not null,
department varchar(25) not null,
phone varchar(25),
address varchar(50),
salary int);''')
connection.commit()
connection.close()
关闭与数据库的连接后,该连接对象将不再连接到数据库。您必须使用重新连接到数据库
connection = psycopg2.connect(database = "staff", user = "XYZ", password = "python", host = "localhost", port = "5432")
或者,您可以做您需要做的事情,只在完成与数据库的交互时关闭连接。这不起作用。需要找到一种方法来获得连接,而无需再次编写这些连接命令。@AakarshAnubhav您能澄清一下代码的上下文吗?将所有必要的代码放在connection.commit()和connection.close()之间不需要重新连接。当你有更多的时间与数据库交互时,你能解释一下你关闭连接的具体原因吗?我明白了。我将仅在完成与数据库的交互后关闭连接。如果要重新使用连接,请不要在脚本末尾调用
connection.close()
。打开连接的函数调用已经在其中:psycopg2.connect()