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)
复制代码

看看执行结果

 

 数据库查询下数据

 

 

 




posted @   明矾  阅读(1811)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示