zoukankan      html  css  js  c++  java
  • psycopg2笔记

    建立连接

    1. 使用*.ini文件(python的configparser包可以解析这种类型的配置文件)保存数据库连接的配置信息。
    2. 使用psycopg2.connect函数获得connection对象。
    3. 使用connection对象创建cursor对象。
    4. 使用cursor对象执行sql语句提交或者回滚transaction。
    5. 使用cursor对象fetchone获得查询结果。
    6. 关闭cursor对象和connection对象。

    创建数据表

    过程:

    1. 构造建表的sql语句
    2. 调用psycopg2.connect()方法获得connection对象
    3. 调用connection.cursor()方法获得cursor对象
    4. 调用cursor.execute()方法执行sql语句
    5. 调用connection.commit方法提交事务
    6. 调用cursor.close()和connection.close()方法关闭连接

    插入行

    1. 构造插入语句, 使用%s作为占位符,执行时psycopg2会用值智能替换掉占位符。可以添加RETURNING字句,来得到自动生成的字段值。
    2. 创建数据表的2,3。获得connection对象和cursor对象
    3. 使用cursor.execute方法来插入一行,使用cursor.executemany方法来插入多行。 execute方法的第一个参数是sql语句,第二个参数是值的tuple。executemany方法的第一个参数是sql语句,第二个参数是list of tuple。
    4. 如果在1中使用了RETURNING子句,可以使用cursor.fetchone方法,来获得返回的自动生成字段的值。
    5. 同上5
    6. 同上6

    更新数据

    1. 基本上和插入行相同。
    2. 使用cursor.rowcount属性来获得受影响的行的数目。

    transaction

    1. connection对象负责管理事务。当你第一次使用cursor.execute方法执行sql语句的时候事务开启,这以后的所有sql语句都在这个事务中执行,直到connection.commit或者connection.rollback或者del connection或者connection.close被调用,事务才结束。

    2. 一个简单的select语句可能会开启一个事务并且对相应的表格加锁,所以如果你是在开发一个长时间运行的应用,而且一个连接长时间不使用,那么你需要调用commit或者rollback方法结束事务,避免不必要的问题。

    3. 使用connection.autocommit来控制事务

    4. 从psycopg2.5开始,connection和cursor都是context manager对象,可以在with ... as ...语句中使用。值得注意的是,离开with语句后,connection对象不会被close,它只是结束提交或者回滚事务。所以可以在多个with语句中使用connection对象。

    调用存储过程

    1. 使用cursor.callproc('function name', tuple), 函数的第一个参数是存储过程的名字,函数的第二个参数是实参tuple。这个调用和cursor.execute('select * from functionanme(%s)', tuple)相同。
    2. 可以使用cursor.fetchone, cursor.fetchmany, cursor.fetchall来获得返回值。

    blob对象

    1. 使用psycopg2.Binary对象和postgresql的BYTEA数据类型对应,用于存储二进制数据。

    2. 以下这个例子演示了二进制数据的存取。

    3. config.py

    
    
    def config():
    
    
        db_conn_config = {
            'host': 'localhost',
            'user': 'postgres',
            'password': '',
            'dbname': 'test',
            'port': 5432
        }
    
        return db_conn_config
        
    
    • write_blob.py
    
    import psycopg2
    from config import config
     
     
    def write_blob(path_to_file):
        """ insert a BLOB into a table """
        conn = None
        try:
            # read data from a picture
            drawing = open(path_to_file, 'rb').read()
            # read database configuration
            params = config()
            # connect to the PostgresQL database
            conn = psycopg2.connect(**params)
            # create a new cursor object
            cur = conn.cursor()
            # execute the INSERT statement
            cur.execute("INSERT INTO parts_drawings(drawing_data,name) " +
                        "VALUES(%s,%s)",
                        (psycopg2.Binary(drawing), path_to_file))
            # commit the changes to the database
            conn.commit()
            # close the communication with the PostgresQL database
            cur.close()
        except (Exception, psycopg2.DatabaseError) as error:
            print(error)
        finally:
            if conn is not None:
                conn.close()
    
    if __name__ == '__main__':
        write_blob('./1.jpg')
    
    • read_blob.py
    
    from config import config
    import psycopg2
    def read_blob(id, path_to_dir):
        """ read BLOB data from a table """
        conn = None
        try:
            # read database configuration
            params = config()
            # connect to the PostgresQL database
            conn = psycopg2.connect(**params)
            # create a new cursor object
            cur = conn.cursor()
            # execute the SELECT statement
            cur.execute(""" SELECT *
                            FROM parts_drawings                        
                            WHERE id = %s """,
                        (id,))
     
            blob = cur.fetchone()
            open(path_to_dir + str(blob[0]) + '.jpg', 'wb').write(blob[1])
            # close the communication with the PostgresQL database
            cur.close()
        except (Exception, psycopg2.DatabaseError) as error:
            print(error)
        finally:
            if conn is not None:
                conn.close()
    
    if __name__ == '__main__':
        read_blob(1, './img/')
    
    

    查询数据

    1. 查询数据和其它操作类似。
    2. 可以使用cursor.fetchone, cursor.fetchall, cursor.fetchmany(size=cursor.arraysize)方法来返回查询结果。fetchone返回一个tuple或者None, fetchall返回一个list of tuple,如果没有结果则返回一个空的tuple。fetchmany返回list of tuple, list的长度由size参数决定,size的默认值是cursor.arraysize, 如果没有结果可以返回,那么返回一个空的list。

    删除数据

    1. 和更新数据类似
    2. 可以使用cursor.rowcount来获得删除的行数目。
  • 相关阅读:
    Android DSelectorBryant 单选滚动选择器
    Android BSearchEdit 搜索结果选择框
    Android TeaScreenPopupWindow多类型筛选弹框
    Android TeaPickerView数据级联选择器
    Android 兔子基金小工具
    Android 监听手机锁屏的工具类
    Android 弹出Dialog时隐藏状态栏和底部导航栏
    Android Studio 3.0+ Record Espresso Test 自动化测试
    Android GZIP压缩与解压
    体验 OpenDiablo2, 一款Golang开发的开源游戏
  • 原文地址:https://www.cnblogs.com/hao-ming/p/7215050.html
Copyright © 2011-2022 走看看