• 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)

    看看执行结果

     数据库查询下数据




  • 相关阅读:
    生产者—消费者模型
    使用wait/notify/notifyAll实现线程间通信的几点重要说明
    死锁
    python基础:协程详解
    python爬虫:multipart/form-data格式的POST实体封装与提交
    python爬虫:Multipart/form-data POST文件上传详解
    python爬虫:http请求头部(header)详解
    python爬虫:登录百度账户,并上传文件到百度云盘
    python爬虫:urlparse模块拆分url
    转:python爬虫:html标签(图文详解二)
  • 原文地址:https://www.cnblogs.com/mingfan/p/13593757.html
Copyright © 2020-2023  润新知