zoukankan      html  css  js  c++  java
  • 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)

    看看执行结果

     数据库查询下数据




  • 相关阅读:
    Hashmap
    string字符串分词
    关于链表的几道经典例题
    【C语言】链表(LinkedList)的建立与基本操作
    01迷宫
    2019 数学联赛 题解 / 游记
    一种简单方法构造 n 元有限域
    Python逆向某网站之 AES解密数据
    我发现了一个网站Bug,然后反馈了
    在多线程中使用静态方法是否有线程安全问题
  • 原文地址:https://www.cnblogs.com/mingfan/p/13593757.html
Copyright © 2011-2022 走看看