使用 Python 连接到 PSQL 数据库

Connection to PSQL database using Python

查看下面使用 Python 在 PSQL 中创建 table 的命令。在 connection.close() 之后是否有任何命令可以打开连接或再次获取到数据库的连接,这样我们就不需要编写整个命令来获取连接并且可以轻松地更改创建的 table 中的数据? ?

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")

或者,您可以执行您需要执行的操作,仅在完成与数据库的交互后关闭连接。