psycopg2 庫是 python 用來操作 PostgreSQL 數據庫的第三方庫
首先需要有一個,pg的數據庫,於是docker直接實例化一個
docker run --name pg12 -e POSTGRES_PASSWORD=123456 -p5432:5432 -d postgres
登進去看看
[root@localhost postgres]# docker exec -it pg12 /bin/bash root@90cdc487c64e:/# psql -U postgres psql (12.4 (Debian 12.4-1.pgdg100+1)) Type "help" for help. postgres=# \l List of databases Name | Owner | Encoding | Collate | Ctype | Access privileges -----------+----------+----------+------------+------------+----------------------- postgres | postgres | UTF8 | en_US.utf8 | en_US.utf8 | template0 | postgres | UTF8 | en_US.utf8 | en_US.utf8 | =c/postgres + | | | | | postgres=CTc/postgres template1 | postgres | UTF8 | en_US.utf8 | en_US.utf8 | =c/postgres + | | | | | postgres=CTc/postgres (3 rows)
python操作
首先引入psycopg2
import psycopg2
封裝打開和關閉數據庫連接的函數
def connect_db(): try: conn = psycopg2.connect(database='postgres', user='postgres', password='123456', host='192.168.101.9', port=5432) except Exception as e: print('connection failed') else: return conn def close_db_connection(conn): conn.commit() conn.close()
執行語句
psycopg2 提供了一個
cursor
類,用來在數據庫 Session 里執行 PostgreSQL 命令
cursor
對象由
connection.cursor()
方法創建
執行 SQL 命令后的返回結果由
cur.fetchall()
接收為一個元組的列表。
def execute_sql(): conn = connect_db() if not conn: return cur = conn.cursor() cur.execute("create table tab1(name varchar ,age int)") cur.execute("insert into tab1 values('tom' ,18)") cur.execute("select * from tab1") result=cur.fetchall() print(result) close_db_connection(conn)
看看執行結果
數據庫查詢下數據