使用Python進(jìn)行PostgreSQL數(shù)據(jù)庫(kù)連接的流程步驟
使用python進(jìn)行PostgreSQL 數(shù)據(jù)庫(kù)連接
PostgreSQL 數(shù)據(jù)庫(kù)是最常用的關(guān)系型數(shù)據(jù)庫(kù)之一,最吸引人的一點(diǎn)是它作為開源數(shù)據(jù)庫(kù)且具有可拓展性,能夠提供豐富的應(yīng)用。運(yùn)用python可以很簡(jiǎn)單的建立PostgreSQL 數(shù)據(jù)庫(kù)連接,其中最受歡迎的就是psycopg。
1. 安裝psycopg2
Psycopy是針對(duì)python的Postgres 數(shù)據(jù)庫(kù)的適配模塊,安裝psycopg2可以整合python和Postgres 。使用cmd輸入命令進(jìn)行安裝:
pip install psycopg2
也可以在pycharm中查找psycopg2安裝包:

2. 圖形化連接數(shù)據(jù)庫(kù)
在pycharm中選擇Database,點(diǎn)擊左上角的+添加數(shù)據(jù)庫(kù),選擇postgresql:
創(chuàng)建數(shù)據(jù)庫(kù)連接后點(diǎn)擊apply,數(shù)據(jù)庫(kù)會(huì)顯示在右側(cè)窗格中。


3. 代碼連接數(shù)據(jù)庫(kù)
3.1 不使用配置文件
下面使用 psycopy2.connect()方法連接到postgresql數(shù)據(jù)庫(kù)。通過調(diào)用cursor類中的execute()方法對(duì)數(shù)據(jù)庫(kù)進(jìn)行操作。在execute()中用SQL語(yǔ)句創(chuàng)建表。使用commit()將數(shù)據(jù)發(fā)送到數(shù)據(jù)庫(kù)服務(wù)器,最后使用close()關(guān)閉數(shù)據(jù)庫(kù)。commit()能夠?qū)?shù)據(jù)庫(kù)進(jìn)行改變,且不可逆。
connect() 方法的參數(shù)一般包括:
- database: 要連接的數(shù)據(jù)庫(kù)名稱
- user:連接數(shù)據(jù)庫(kù)的用戶名
- password: 連接數(shù)據(jù)庫(kù)的密碼
- host: 數(shù)據(jù)庫(kù)端口的地址,一般為 “localhost”,或者主機(jī)的IP地址
- port: 門戶 默認(rèn)為5432.
import psycopg2 con = psycopg2.connect(database=“postgres”, user=“fbase”, password=“123456”, host=“192.168.198.152”, port=“8432”) print(con) print(“Database opened successfully”) cur = con.cursor() cur.execute(‘SELECT version()') db_version = cur.fetchone() print(db_version) con.close()
運(yùn)行結(jié)果如下:

3.2 使用配置文件
可以使用配置文件來(lái)存儲(chǔ)所有連接參數(shù)。
database.ini文件的內(nèi)容如下:
[postgresql] host = 192.168.198.152 database = postgres user = fbase password = 123456 port = 8432
下面的config()函數(shù)會(huì)讀取database.ini文件并返回連接參數(shù)。該config()函數(shù)放置在config.py文件中:
from configparser import ConfigParser
def config(filename='../../resource/database.ini', section='postgresql'):
# create a parser
parser = ConfigParser()
# read config file
parser.read(filename)
# get section, default to postgresql
db = {}
if parser.has_section(section):
params = parser.items(section)
for param in params:
db[param[0]] = param[1]
else:
raise Exception('Section {0} not found in the {1} file'.format(section, filename))
return db
下面的connect()函數(shù)連接到suppliers數(shù)據(jù)庫(kù)并打印出 PostgreSQL 數(shù)據(jù)庫(kù)版本。
import psycopg2
from demo.pgdemo.config import config
def connect():
""" Connect to the PostgreSQL database server """
conn = None
try:
# read connection parameters
params = config()
# connect to the PostgreSQL server
print('Connecting to the PostgreSQL database...')
conn = psycopg2.connect(**params)
# create a cursor
cur = conn.cursor()
# execute a statement
print('PostgreSQL database version:')
cur.execute('SELECT version()')
# display the PostgreSQL database server version
db_version = cur.fetchone()
print(db_version)
# close the communication with the PostgreSQL
cur.close()
except (Exception, psycopg2.DatabaseError) as error:
print(error)
finally:
if conn is not None:
conn.close()
print('Database connection closed.')
if __name__ == '__main__':
connect()
怎么運(yùn)行的。
- 首先,從
database.ini文件中讀取數(shù)據(jù)庫(kù)連接參數(shù)。 - 接下來(lái),通過調(diào)用
connect()函數(shù)創(chuàng)建一個(gè)新的數(shù)據(jù)庫(kù)連接。 - 然后,新建一個(gè)
cursor并執(zhí)行SQL語(yǔ)句來(lái)獲取 PostgreSQL 數(shù)據(jù)庫(kù)版本。 - 之后,通過調(diào)用游標(biāo)對(duì)象的
fetchone()方法讀取結(jié)果集。 - 最后,通過調(diào)用
cursor和connection對(duì)象的close()方法關(guān)閉與數(shù)據(jù)庫(kù)服務(wù)器的通信。
4. DML語(yǔ)句測(cè)試
4.1 創(chuàng)建表
使用SQL(Structured Query Language)語(yǔ)句CREATE TABLE添加新的表:
import psycopg2
# 建立數(shù)據(jù)庫(kù)連接
con = psycopg2.connect(database="postgres",
user="fbase",
password="123456",
host="192.168.198.152",
port="8432")
print("Database opened successfully")
# 調(diào)用游標(biāo)對(duì)象
cur = con.cursor()
# 用cursor中的execute 使用DDL語(yǔ)句創(chuàng)建一個(gè)名為 STUDENT 的表,指定表的字段以及字段類型
cur.execute('''
CREATE TABLE IF NOT EXISTS STUDENT
(ADMISSION INT PRIMARY KEY NOT NULL,
NAME TEXT NOT NULL,
AGE INT NOT NULL,
COURSE CHAR(50),
DEPARTMENT CHAR(50));''')
# 提交更改,增添或者修改數(shù)據(jù)只會(huì)必須要提交才能生效
con.commit()
con.close()
結(jié)果查看:
postgres=# d
List of relations
Schema | Name | Type | Owner
--------+---------+-------+-------
public | student | table | fbase
(1 row)4.2 表插入數(shù)據(jù)
使用INSERT INTO 在以經(jīng)生成的表中插入數(shù)據(jù)
import psycopg2
# 建立數(shù)據(jù)庫(kù)連接
con = psycopg2.connect(database="postgres",
user="fbase",
password="123456",
host="192.168.198.152",
port="8432")
print("Database opened successfully")
# 調(diào)用游標(biāo)對(duì)象
cur = con.cursor()
# 在表中插入一條數(shù)據(jù)
cur.execute("INSERT INTO STUDENT (ADMISSION,NAME,AGE,COURSE,DEPARTMENT) "
"VALUES (3420, 'John', 18, 'Computer Science', 'ICT')")
# 提交更改,增添或者修改數(shù)據(jù)只會(huì)必須要提交才能生效
con.commit()
con.close()
結(jié)果查看:
postgres=# select * from student ;
admission | name | age | course | department
-----------+------+-----+----------------------------------------------------+----------------------------------------------------
3420 | John | 18 | Computer Science | ICT
(1 row)4.3 表更新數(shù)據(jù)
同樣使用SQL語(yǔ)句更新目標(biāo)字段,使用commit()更新數(shù)據(jù)庫(kù)
import psycopg2
# 建立數(shù)據(jù)庫(kù)連接
con = psycopg2.connect(database="postgres",
user="fbase",
password="123456",
host="192.168.198.152",
port="8432")
print("Database opened successfully")
# 調(diào)用游標(biāo)對(duì)象
cur = con.cursor()
# 更新表中的數(shù)據(jù)
cur.execute("UPDATE student set name = 'joe' WHERE admission = 3420")
# 提交更改,增添或者修改數(shù)據(jù)只會(huì)必須要提交才能生效
con.commit()
con.close()
結(jié)果查看:
postgres=# select * from student ;
admission | name | age | course | department
-----------+------+-----+----------------------------------------------------+----------------------------------------------------
3420 | John | 18 | Computer Science | ICT
(1 row)
postgres=# select * from student ;
admission | name | age | course | department
-----------+------+-----+----------------------------------------------------+----------------------------------------------------
3420 | joe | 18 | Computer Science | ICT
(1 row)4.4 表刪除數(shù)據(jù)
同樣使用SQL語(yǔ)句更新目標(biāo)字段,使用commit()更新數(shù)據(jù)庫(kù)
import psycopg2
# 建立數(shù)據(jù)庫(kù)連接
con = psycopg2.connect(database="postgres",
user="fbase",
password="123456",
host="192.168.198.152",
port="8432")
print("Database opened successfully")
# 調(diào)用游標(biāo)對(duì)象
cur = con.cursor()
# 刪除表中的數(shù)據(jù)
cur.execute("DELETE FROM student WHERE admission = 3420")
# 提交更改,增添或者修改數(shù)據(jù)只會(huì)必須要提交才能生效
con.commit()
con.close()
結(jié)果查看:
postgres=# select * from student ;
admission | name | age | course | department
-----------+------+-----+----------------------------------------------------+----------------------------------------------------
3420 | joe | 18 | Computer Science | ICT
(1 row)
postgres=# select * from student ;
admission | name | age | course | department
-----------+------+-----+--------+------------
(0 rows)5. DQL語(yǔ)句測(cè)試
5.1 查看表中的數(shù)據(jù)
同樣使用SQL語(yǔ)句更新目標(biāo)字段,使用commit()更新數(shù)據(jù)庫(kù)
import psycopg2
# 建立數(shù)據(jù)庫(kù)連接
con = psycopg2.connect(database="postgres",
user="fbase",
password="123456",
host="192.168.198.152",
port="8432")
print("Database opened successfully")
# 調(diào)用游標(biāo)對(duì)象
cur = con.cursor()
# 刪除表中的數(shù)據(jù)
cur.execute("SELECT * FROM student")
rows = cur.fetchall()
for row in rows:
print("ADMISSION =", row[0])
print("NAME =", row[1])
print("AGE =", row[2])
print("COURSE =", row[3])
print("DEPARTMENT =", row[4], "
")
# 提交更改,增添或者修改數(shù)據(jù)只會(huì)必須要提交才能生效
con.commit()
con.close()
結(jié)果查看:
D:python3python.exe D:/project/python/demo/demo/pgdemo/dql_select_1.py
Database opened successfully
ADMISSION = 3420
NAME = John
AGE = 18
COURSE = Computer Science
DEPARTMENT = ICT
w[3])
print("DEPARTMENT =", row[4], "
")
# 提交更改,增添或者修改數(shù)據(jù)只會(huì)必須要提交才能生效
con.commit()
con.close()
結(jié)果查看:
D:python3python.exe D:/project/python/demo/demo/pgdemo/dql_select_1.py Database opened successfully ADMISSION = 3420 NAME = John AGE = 18 COURSE = Computer Science DEPARTMENT = ICT
以上就是使用Python進(jìn)行PostgreSQL數(shù)據(jù)庫(kù)連接的流程步驟的詳細(xì)內(nèi)容,更多關(guān)于Python連接PostgreSQL數(shù)據(jù)庫(kù)的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
一小時(shí)學(xué)會(huì)TensorFlow2之Fashion Mnist
這篇文章主要介紹了TensorFlow2之Fashion Mnist,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-09-09
使用Python實(shí)現(xiàn)不同需求的排行榜功能
這篇文章主要為大家介紹了Python實(shí)現(xiàn)不同需求的排行榜功能,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2024-01-01
Python基礎(chǔ)之?dāng)?shù)據(jù)結(jié)構(gòu)詳解
這篇文章主要介紹了Python基礎(chǔ)之?dāng)?shù)據(jù)結(jié)構(gòu)詳解,文中有非常詳細(xì)的代碼示例,對(duì)正在學(xué)習(xí)python基礎(chǔ)的小伙伴們有非常好的幫助,需要的朋友可以參考下2021-04-04
Python讀取圖像并顯示灰度圖的實(shí)現(xiàn)
這篇文章主要介紹了Python讀取圖像并顯示灰度圖的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-12-12
Python實(shí)現(xiàn)讀取Excel表數(shù)據(jù)并轉(zhuǎn)為JSON格式文件
這篇文章主要為大家詳細(xì)介紹了Python如何使用pandas庫(kù)讀取Excel表并將其轉(zhuǎn)為JSON格式文件,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以參考下2025-04-04
Python實(shí)現(xiàn)快捷啟動(dòng)本地應(yīng)用
這篇文章主要為大家詳細(xì)介紹了如何使用Python實(shí)現(xiàn)一個(gè)快捷啟動(dòng)器,可以實(shí)現(xiàn)快速啟動(dòng)本地應(yīng)用和文件秒開,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2025-07-07
Python 機(jī)器學(xué)習(xí)第一章環(huán)境配置圖解流程
機(jī)器學(xué)習(xí)是一類算法的總稱,這些算法企圖從大量歷史數(shù)據(jù)中挖掘出其中隱含的規(guī)律,并用于預(yù)測(cè)或者分類,更具體的說(shuō),機(jī)器學(xué)習(xí)可以看作是尋找一個(gè)函數(shù),輸入是樣本數(shù)據(jù),輸出是期望的結(jié)果,只是這個(gè)函數(shù)過于復(fù)雜,以至于不太方便形式化表達(dá)2021-11-11
從安裝到精通詳解Python包管理神器pip完全指南(小白友好版)
本文是一篇Python包管理工具pip的全面指南,從基礎(chǔ)到進(jìn)階介紹了pip的核心功能和使用技巧,全文采用通俗易懂的語(yǔ)言,適合Python初學(xué)者,快跟隨小編一起學(xué)習(xí)一下吧2026-03-03
Python實(shí)現(xiàn)對(duì)Excel表格的操作詳解
這篇文章主要介紹了Python實(shí)現(xiàn)對(duì)Excel表格的操作,在數(shù)據(jù)處理和報(bào)告生成等工作中,Excel表格是一種常見且廣泛使用的工具,使用Python來(lái)處理Excel表格能夠大大的提升效率,感興趣的同學(xué)可以參考下2024-02-02

