PyGreSQL入门,pg模块,pgdb模块

安装:http://www.pygresql.org/contents/install.html

 

 

PyGreSQL入门

——简单整理翻译自官方文档:http://www.pygresql.org/contents/tutorial.html

  • 创建数据库连接

只需import DB类并创建一个实例,填入相应的连接信息,例:

如果省略参数,则会使用默认值:

dbname,user默认为当前系统用户,host为localhost,port为5432。

  • 执行SQL语句

DB.query()

  • 获取所有表名

DB.get_tables(),类似psql中d:

  • 获取表属性

DB.get_attnames(),类似psql中d table:

  • 检查权限

DB.has_table_privilege()

  • 插入数据

DB.insert()   –注:GP不支持

该方法将完整的行作为字典返回,包括自增列。可以将字典赋值给变量:

  • 批量插入数据

Connection.inserttable()

在插入大量数据时,批量插入性能比单条插入快很多

  • 查询数据

DB.query()

将查询结果放入元组:

或字典:

或named tuple:

使用DB.get_as_dict()可以轻松的将整张表数据加载到Python 字典中:

  • 修改数据

DB.update()

也可使用DB.query()

返回值:‘7’表示更新的行数。

  • 删除数据

DB.delete()

1表示删除的行数,再次执行就会显示0行被删除:

  • 删除表
  • 关闭连接

更高级的特性和详细信息,参阅:http://www.pygresql.org/contents/pg/index.html

接口:

The Classic PyGreSQL Interface

Contents

pgdb — The DB-API Compliant Interface

A PostgreSQL Primer

The examples in this chapter of the documentation have been taken from the PostgreSQL manual. They demonstrate some PostgreSQL features using the classic PyGreSQL interface. They can serve as an introduction to PostgreSQL, but not so much as examples for the use of PyGreSQL.

原文地址:https://www.cnblogs.com/timssd/p/10212563.html