使用psycopg2连接postgresql,首先需要安装python psycopg2依赖包

# 下载 psycopg2 模块
pip install psycopg2

然后引用psycopg2,调用psycopg2.connect接口,实现postgresql连接,进而查询或更新postgresql数据。

注意:在插入数据时,需要commit提交。由于总是忘记,所以我是增删改查都会写上

import psycopg2

conn = psycopg2.connect(database="tables", user="postgres", password="***", host="127.0.0.1", port="5432")
cur = conn.cursor()

# 执行sql语句 查询
cur.execute("SELECT name, years from students")
# 获取所有
rows = cur.fetchall()


# 提交 , 关闭数据库
# 如果只是查询可以只是 conn .close()    
# 如果是修改了数据库就要都写 
conn .commit()
cur.close()
conn .close()

 注意 : 如果在查询的时候附加了条件,比如只是查询某天的数据,或者取一条数据(pg可以存储json格式),那么就要使用 fetchone()[0]

# 获取的一条数据
row = cur.fetchone()[0]

注意 : 如果在表中的字段这样 , 那么我们在查询的时候,比如查询 2020-01-10 日期的学生数据 

CREATE TABLE students
(
    id            serial primary key,      # id
    create_date   date   not null default current_date,     # 创建时间
    modified_date timestamp       default current_timestamp,   # 写入时间
    modified_user varchar         default current_user,     # 所属者
    data          jsonb  not null    # 存储学生信息 , 比如 json中放全校学生的名字/年龄/成绩等
);
import psycopg2

conn = psycopg2.connect(database="tables", user="postgres", password="***", host="127.0.0.1", port="5432")
cur = conn.cursor()

date = "2020-01-10"
date_param = f'\'{date}\''   # 转个格式


# 执行sql语句 查询
cur.execute("SELECT data from students where create_date = {date_param}")
# 获取所有
student = cur.fetchone()[0]


# 提交 , 关闭数据库
# 如果只是查询可以只是 conn .close()    
# 如果是修改了数据库就要都写 
conn .commit()
cur.close()
conn .close()