Skip to content

Latest commit

 

History

History
143 lines (96 loc) · 2.79 KB

File metadata and controls

143 lines (96 loc) · 2.79 KB
Error in user YAML: (<unknown>): found a tab character that violate indentation while scanning a plain scalar at line 3 column 3
---
- oeasy Python 0511
- 这是 oeasy 系统化 Python 教程,从基础一步步讲,扎实、完整、不跳步。愿意花时间学,就能真正学会。
- 本教程同步发布在: 
	- 个人网站: `https://oeasy.org` 
	- 蓝桥云课: `https://www.lanqiao.cn/courses/3584` 
	- GitHub: `https://github.com/overmind1980/oeasy-python-tutorial` 
	- Gitee: `https://gitee.com/overmind1980/oeasypython` 
---

psycopg3

回忆

  • 上次安装了
    • postgres数据库
    • psycopg3 适配器

图片描述

  • psycopg3
    • 如何适配 postgres 呢?

直接psql连接

  • 我们先看看 客户端psql 是如何连接数据库的

图片描述

  • 构造连接字符串

字符串

psql -d oeasydb -h localhost -p 5432 -U postgres -W 
  • 密码不对
    • 需要去pg里面改密码

图片描述

修改密码

  • 先进入pg
ALTER USER 
    postgres 
WITH PASSWORD 
    'oeasypg'
;
  • 修改完成

图片描述

尝试登陆

  • 修改postgres密码后
    • 退出pg
    • 再尝试登录
psql -d oeasydb -h localhost -p 5432 -U postgres -W 
  • 输入刚才修改的密码oeasypg
    • 注意输入密码时
      • 终端不显示任何字符

图片描述

  • 确实可以连接到指定库oeasydb
  • 尝试用psycopg3

查看文档

图片描述

  • 有关于connect函数的说明

connect

图片描述

  • conninfo很重要

conninfo

图片描述

  • 尝试做一个

照猫画虎

  • 具体代码 包括
    • 用户名
    • 密码
    • 主机地址
    • 端口号
    • 数据库名
import psycopg
conninfo = "postgres://postgres:oeasypg@localhost:5432/oeasydb"
with psycopg.connect(conninfo) as conn:
    print("connect!")
  • 点击右上角复制按钮后
  • 键入 vi c.py
  • 依次按下 "*p 三个按键

图片描述

  • 运行结果

图片描述

  • 可以连到库里面
    • 直接查询吗?

总结

  • 这次研究了psycopg这个包
    • pg最流行的python适配器
    • 有了他就可以用python对数据库读写!

图片描述

  • 具体怎么读写呢?🤔
  • 下次再说!👋

  • 本文来自 oeasy Python 系统教程。
  • 想完整、扎实学 Python,
  • 搜索 oeasy 即可。