python之psycopg2操作PostgreSQL
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)
看看执行结果
数据库查询下数据
但行好事,莫问前程
分类:
Python
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了