Skip to content

Latest commit

 

History

History
157 lines (109 loc) · 3.45 KB

File metadata and controls

157 lines (109 loc) · 3.45 KB
Error in user YAML: (<unknown>): could not find expected ':' while scanning a simple key at line 3 column 1
---
- oeasy Python 0513
- 这是 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

回忆

  • 上次可以
    • 执行sql语句
      • create table
      • insert

图片描述

  • 可以 通过python来进行查询吗?
    • 可以 得到select查询的结果 吗?

检查环境

  • 确实建了表
  • 也插了数据

图片描述

  • 可以在python中进行查询吗?

观察文档

图片描述

尝试使用

import psycopg
conninfo = "postgres://postgres:oeasypg@localhost:5432/oeasydb"
with psycopg.connect(conninfo) as conn:
    print("connect!")
    with conn.cursor() as cur:
        cur.execute("SELECT * FROM test;")
        for record in cur.fetchall():
            print(record)
  • 具体代码

图片描述

  • 运行结果

图片描述

  • 只有一条记录
  • 尝试多插几条记录

插入数据

  • vi c2.py
import psycopg
conninfo = "postgres://postgres:oeasypg@localhost:5432/oeasydb"
with psycopg.connect(conninfo) as conn:
    print("connect!")
    conn.execute(
        "INSERT INTO test(num, data) VALUES (%s, %s)",
        (200, "efg")
    )
    conn.execute(
        "INSERT INTO test(num, data) VALUES (%s, %s)",
        (300, "hij")
    )
    print("Data is inserted!")
    conn.commit()
  • 执行过c2.py后

图片描述

  • 再go.py查看

再次查看

  • 新数据已经插入
    • 可以 通过游标(cursor)
    • 查询到多个元组

图片描述

  • 如何理解 游标 呢?

游标(cursor)

  • 什么是游标(cursor)呢?
    • 游标是给pg服务器发送命令的一个会话
    • 使用相同Connection的会话是相通的

图片描述

python DBAPI中的游标

图片描述

  • 游标可以执行sql语句
  • psycopg是如何实现的呢?

pg的游标

  • 通过调用postgres的接口实现的

图片描述

ibm定义的游标

图片描述

  • 游标可以通过SELECT 语句
    • 获得一系列的结果集

总结

  • 这次使用了游标
  • 通过游标
    • 可以得到select查询的结果集
  • 这样我们就可以
    • 通过python语言
      • 直接操作postgres了

图片描述

  • psycopg还有什么好玩的吗🤔
  • 下次再说!👋

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