[英]Connection to PSQL database using Python
查看以下命令,使用 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()
關閉與數據庫的連接后,該連接 object 不再連接到數據庫。 您將不得不重新連接到數據庫
connection = psycopg2.connect(database = "staff", user = "XYZ", password = "python", host = "localhost", port = "5432")
或者,您可以做您需要做的事情,僅在您完成與數據庫的交互后關閉連接。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.