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

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


3. 代碼連接數(shù)據(jù)庫
3.1 不使用配置文件
下面使用 psycopy2.connect()方法連接到postgresql數(shù)據(jù)庫。通過調(diào)用cursor類中的execute()方法對數(shù)據(jù)庫進行操作。在execute()中用SQL語句創(chuàng)建表。使用commit()將數(shù)據(jù)發(fā)送到數(shù)據(jù)庫服務器,最后使用close()關閉數(shù)據(jù)庫。commit()能夠?qū)?shù)據(jù)庫進行改變,且不可逆。
connect() 方法的參數(shù)一般包括:
- database: 要連接的數(shù)據(jù)庫名稱
- user:連接數(shù)據(jù)庫的用戶名
- password: 連接數(shù)據(jù)庫的密碼
- host: 數(shù)據(jù)庫端口的地址,一般為 “localhost”,或者主機的IP地址
- port: 門戶 默認為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()
運行結果如下:

3.2 使用配置文件
可以使用配置文件來存儲所有連接參數(shù)。
database.ini文件的內(nèi)容如下:
[postgresql] host = 192.168.198.152 database = postgres user = fbase password = 123456 port = 8432
下面的config()函數(shù)會讀取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ù)庫并打印出 PostgreSQL 數(shù)據(jù)庫版本。
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()怎么運行的。
- 首先,從
database.ini文件中讀取數(shù)據(jù)庫連接參數(shù)。 - 接下來,通過調(diào)用
connect()函數(shù)創(chuàng)建一個新的數(shù)據(jù)庫連接。 - 然后,新建一個
cursor并執(zhí)行SQL語句來獲取 PostgreSQL 數(shù)據(jù)庫版本。 - 之后,通過調(diào)用游標對象的
fetchone()方法讀取結果集。 - 最后,通過調(diào)用
cursor和connection對象的close()方法關閉與數(shù)據(jù)庫服務器的通信。
4. DML語句測試
4.1 創(chuàng)建表
使用SQL(Structured Query Language)語句CREATE TABLE添加新的表:
import psycopg2
# 建立數(shù)據(jù)庫連接
con = psycopg2.connect(database="postgres",
user="fbase",
password="123456",
host="192.168.198.152",
port="8432")
print("Database opened successfully")
# 調(diào)用游標對象
cur = con.cursor()
# 用cursor中的execute 使用DDL語句創(chuàng)建一個名為 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ù)只會必須要提交才能生效
con.commit()
con.close()
結果查看:
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ù)庫連接
con = psycopg2.connect(database="postgres",
user="fbase",
password="123456",
host="192.168.198.152",
port="8432")
print("Database opened successfully")
# 調(diào)用游標對象
cur = con.cursor()
# 在表中插入一條數(shù)據(jù)
cur.execute("INSERT INTO STUDENT (ADMISSION,NAME,AGE,COURSE,DEPARTMENT) "
"VALUES (3420, 'John', 18, 'Computer Science', 'ICT')")
# 提交更改,增添或者修改數(shù)據(jù)只會必須要提交才能生效
con.commit()
con.close()
結果查看:
postgres=# select * from student ;
admission | name | age | course | department
-----------+------+-----+----------------------------------------------------+----------------------------------------------------
3420 | John | 18 | Computer Science | ICT
(1 row)
4.3 表更新數(shù)據(jù)
同樣使用SQL語句更新目標字段,使用commit()更新數(shù)據(jù)庫
import psycopg2
# 建立數(shù)據(jù)庫連接
con = psycopg2.connect(database="postgres",
user="fbase",
password="123456",
host="192.168.198.152",
port="8432")
print("Database opened successfully")
# 調(diào)用游標對象
cur = con.cursor()
# 更新表中的數(shù)據(jù)
cur.execute("UPDATE student set name = 'joe' WHERE admission = 3420")
# 提交更改,增添或者修改數(shù)據(jù)只會必須要提交才能生效
con.commit()
con.close()
結果查看:
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語句更新目標字段,使用commit()更新數(shù)據(jù)庫
import psycopg2
# 建立數(shù)據(jù)庫連接
con = psycopg2.connect(database="postgres",
user="fbase",
password="123456",
host="192.168.198.152",
port="8432")
print("Database opened successfully")
# 調(diào)用游標對象
cur = con.cursor()
# 刪除表中的數(shù)據(jù)
cur.execute("DELETE FROM student WHERE admission = 3420")
# 提交更改,增添或者修改數(shù)據(jù)只會必須要提交才能生效
con.commit()
con.close()
結果查看:
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語句測試
5.1 查看表中的數(shù)據(jù)
同樣使用SQL語句更新目標字段,使用commit()更新數(shù)據(jù)庫
import psycopg2
# 建立數(shù)據(jù)庫連接
con = psycopg2.connect(database="postgres",
user="fbase",
password="123456",
host="192.168.198.152",
port="8432")
print("Database opened successfully")
# 調(diào)用游標對象
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], "\n")
# 提交更改,增添或者修改數(shù)據(jù)只會必須要提交才能生效
con.commit()
con.close()
結果查看:
D:\python3\python.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], "\n")
# 提交更改,增添或者修改數(shù)據(jù)只會必須要提交才能生效
con.commit()
con.close()
結果查看:
D:\python3\python.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進行PostgreSQL數(shù)據(jù)庫連接的文章就介紹到這了,更多相關python連接PostgreSQL數(shù)據(jù)庫內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
- Python連接PostgreSQL數(shù)據(jù)庫的方法
- Python實現(xiàn)連接postgresql數(shù)據(jù)庫的方法分析
- python連接PostgreSQL數(shù)據(jù)庫的過程詳解
- Python 操作 PostgreSQL 數(shù)據(jù)庫示例【連接、增刪改查等】
- Python操作PostgreSql數(shù)據(jù)庫的方法(基本的增刪改查)
- Python 中創(chuàng)建 PostgreSQL 數(shù)據(jù)庫連接池
- Python操作PostgreSQL數(shù)據(jù)庫的基本方法(增刪改查)
- Python連接到PostgreSQL數(shù)據(jù)庫的方法詳解
- Python訪問PostgreSQL數(shù)據(jù)庫詳細操作
相關文章
PyQt通過動畫實現(xiàn)平滑滾動的QScrollArea
這篇文章主要為大家詳細介紹了PyQt如何使用Qt的動畫框架 QPropertyAnimation來實現(xiàn)平滑滾動的QScrollArea,文中的示例代碼講解詳細,具有一定的借鑒價值,感興趣的可以學習一下2023-01-01
使用Pandas實現(xiàn)清洗客戶編碼異常數(shù)據(jù)
在不同行業(yè)中,我們經(jīng)常會遇到一個麻煩的問題:數(shù)據(jù)清洗,尤其是當我們需要處理客戶編碼異常數(shù)據(jù)時,下面小編就來和大家分享一下常用的解決辦法吧2023-07-07
使用pandas模塊實現(xiàn)數(shù)據(jù)的標準化操作
這篇文章主要介紹了使用pandas模塊實現(xiàn)數(shù)據(jù)的標準化操作,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-05-05
Python實現(xiàn)一個完整學生管理系統(tǒng)
這篇文章主要為大家詳細介紹了如何利用python實現(xiàn)學生管理系統(tǒng)(面向?qū)ο蟀妫?,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2023-01-01

