0

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

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()
4

1 回答 1

0

关闭与数据库的连接后,该连接对象不再连接到数据库。您将不得不重新连接到数据库

connection = psycopg2.connect(database = "staff", user = "XYZ", password = "python", host = "localhost", port = "5432")

或者,您可以做您需要做的事情,仅在您完成与数据库的交互后关闭连接。

于 2021-04-28T07:30:26.760 回答