PyGreSQL入门,pg模块,pgdb模块
安装:http://www.pygresql.org/contents/install.html
PyGreSQL入门
——简单整理翻译自官方文档:http://www.pygresql.org/contents/tutorial.html
- 创建数据库连接
只需import DB类并创建一个实例,填入相应的连接信息,例:
|
1
2
|
>>> from pg import DB
>>> db = DB(dbname='testdb', host='pgserver', port=5432, user='scott', passwd='tiger')
|
如果省略参数,则会使用默认值:
dbname,user默认为当前系统用户,host为localhost,port为5432。
- 执行SQL语句
DB.query()
|
1
|
>>> db.query("create table fruits(id serial primary key, name varchar)")
|
- 获取所有表名
DB.get_tables(),类似psql中\d:
|
1
2
|
>>> db.get_tables()
['public.fruits']
|
- 获取表属性
DB.get_attnames(),类似psql中\d table:
|
1
2
|
>>> db.get_attnames('fruits')
{'id': 'int', 'name': 'text'}
|
- 检查权限
DB.has_table_privilege()
|
1
2
|
>>> db.has_table_privilege('fruits', 'insert')
True
|
- 插入数据
DB.insert() –注:GP不支持
|
1
2
|
>>> db.insert('fruits', name='apple')
{'name': 'apple', 'id': 1}
|
该方法将完整的行作为字典返回,包括自增列。可以将字典赋值给变量:
|
1
|
>>> banana = db.insert('fruits', name='banana')
|
- 批量插入数据
Connection.inserttable()
在插入大量数据时,批量插入性能比单条插入快很多
|
1
2
3
|
>>> more_fruits = 'cherimaya durian eggfruit fig grapefruit'.split()
>>> data = list(enumerate(more_fruits, start=3))
>>> db.inserttable('fruits', data)
|
- 查询数据
DB.query()
|
1
2
3
4
5
6
7
8
9
10
11
|
>>> print(db.query('select * from fruits'))
id| name
--+----------
1|apple
2|banana
3|cherimaya
4|durian
5|eggfruit
6|fig
7|grapefruit
(7 rows)
|
将查询结果放入元组:
|
1
2
3
|
>>> q = db.query('select * from fruits')
>>> q.getresult()
... [(1, 'apple'), ..., (7, 'grapefruit')]
|
或字典:
|
1
2
|
>>> q.dictresult()
[{'id': 1, 'name': 'apple'}, ..., {'id': 7, 'name': 'grapefruit'}]
|
或named tuple:
|
1
2
3
|
>>> rows = q.namedresult()
>>> rows[3].name
'durian'
|
使用DB.get_as_dict()可以轻松的将整张表数据加载到Python 字典中:
|
1
2
3
4
5
6
7
8
|
>>> db.get_as_dict('fruits', scalar=True)
OrderedDict([(1, 'apple'),
(2, 'banana'),
(3, 'cherimaya'),
(4, 'durian'),
(5, 'eggfruit'),
(6, 'fig'),
(7, 'grapefruit')])
|
- 修改数据
DB.update()
|
1
2
3
4
5
6
7
8
9
|
>>> db.update('fruits', banana, name=banana['name'].capitalize())
{'id': 2, 'name': 'Banana'}
>>> print(db.query('select * from fruits where id between 1 and 3'))
id| name
--+---------
1|apple
2|Banana
3|cherimaya
(3 rows)
|
也可使用DB.query()
|
1
2
|
>>> db.query('update fruits set name=initcap(name)')
'7'
|
返回值:‘7’表示更新的行数。
- 删除数据
DB.delete()
|
1
2
|
>>> db.delete('fruits', banana)
1
|
1表示删除的行数,再次执行就会显示0行被删除:
|
1
2
|
>>> db.delete('fruits', banana)
0
|
- 删除表
|
1
|
>>> db.query("drop table fruits")
|
- 关闭连接
|
1
|
>>> db.close()
|
更高级的特性和详细信息,参阅:http://www.pygresql.org/contents/pg/index.html
接口:
The Classic PyGreSQL Interface
Contents
- Introduction
- Module functions and constants
- connect – Open a PostgreSQL connection
- get/set_defhost – default server host [DV]
- get/set_defport – default server port [DV]
- get/set_defopt – default connection options [DV]
- get/set_defbase – default database name [DV]
- get/set_defuser – default database user [DV]
- get/set_defpasswd – default database password [DV]
- escape_string – escape a string for use within SQL
- escape_bytea – escape binary data for use within SQL
- unescape_bytea – unescape data that has been retrieved as text
- get/set_namedresult – conversion to named tuples
- get/set_decimal – decimal type to be used for numeric values
- get/set_decimal_point – decimal mark used for monetary values
- get/set_bool – whether boolean values are returned as bool objects
- get/set_array – whether arrays are returned as list objects
- get/set_bytea_escaped – whether bytea data is returned escaped
- get/set_jsondecode – decoding JSON format
- get/set_cast_hook – fallback typecast function
- get/set_datestyle – assume a fixed date style
- get/set_typecast – custom typecasting
- cast_array/record – fast parsers for arrays and records
- Type helpers
- Module constants
- Connection – The connection object
- query – execute a SQL command string
- reset – reset the connection
- cancel – abandon processing of current SQL command
- close – close the database connection
- transaction – get the current transaction state
- parameter – get a current server parameter setting
- date_format – get the currently used date format
- fileno – get the socket used to connect to the database
- getnotify – get the last notify from the server
- inserttable – insert a list into a table
- get/set_notice_receiver – custom notice receiver
- putline – write a line to the server socket [DA]
- getline – get a line from server socket [DA]
- endcopy – synchronize client and server [DA]
- locreate – create a large object in the database [LO]
- getlo – build a large object from given oid [LO]
- loimport – import a file to a large object [LO]
- Object attributes
- The DB wrapper class
- Initialization
- pkey – return the primary key of a table
- get_databases – get list of databases in the system
- get_relations – get list of relations in connected database
- get_tables – get list of tables in connected database
- get_attnames – get the attribute names of a table
- has_table_privilege – check table privilege
- get/set_parameter – get or set run-time parameters
- begin/commit/rollback/savepoint/release – transaction handling
- get – get a row from a database table or view
- insert – insert a row into a database table
- update – update a row in a database table
- upsert – insert a row with conflict resolution
- query – execute a SQL command string
- query_formatted – execute a formatted SQL command string
- clear – clear row values in memory
- delete – delete a row from a database table
- truncate – quickly empty database tables
- get_as_list/dict – read a table as a list or dictionary
- escape_literal/identifier/string/bytea – escape for SQL
- unescape_bytea – unescape data retrieved from the database
- encode/decode_json – encode and decode JSON data
- use_regtypes – determine use of regular type names
- notification_handler – create a notification handler
- Attributes of the DB wrapper class
- Query methods
- getresult – get query values as list of tuples
- dictresult – get query values as list of dictionaries
- namedresult – get query values as list of named tuples
- listfields – list fields names of previous query result
- fieldname, fieldnum – field name/number conversion
- ntuples – return number of tuples in query object
- LargeObject – Large Objects
- The Notification Handler
- DbTypes – The internal cache for database types
- Remarks on Adaptation and Typecasting
pgdb — The DB-API Compliant Interface
Contents
- Introduction
- Module functions and constants
- Connection – The connection object
- Cursor – The cursor object
- description – details regarding the result columns
- rowcount – number of rows of the result
- close – close the cursor
- execute – execute a database operation
- executemany – execute many similar database operations
- callproc – Call a stored procedure
- fetchone – fetch next row of the query result
- fetchmany – fetch next set of rows of the query result
- fetchall – fetch all rows of the query result
- arraysize - the number of rows to fetch at a time
- Methods and attributes that are not part of the standard
- Type – Type objects and constructors
- TypeCache – The internal cache for database types
- Remarks on Adaptation and Typecasting
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.
PyGreSQL入门,pg模块,pgdb模块的更多相关文章
- Thinkphp入门 二 —空操作、空模块、模块分组、前置操作、后置操作、跨模块调用(46)
原文:Thinkphp入门 二 -空操作.空模块.模块分组.前置操作.后置操作.跨模块调用(46) [空操作处理] 看下列图: 实际情况:我们的User控制器没有hello()这个方法 一个对象去访问 ...
- Httpd服务入门知识-使用mod_deflate模块压缩页面优化传输速度
Httpd服务入门知识-使用mod_deflate模块压缩页面优化传输速度 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.mod_deflate模块概述 mod_deflate ...
- Python 入门之 内置模块 --logging模块
Python 入门之 内置模块 --logging模块 1.logging -- 日志 (1)日志的作用: <1> 记录用户信息 <2> 记录个人流水 <3> 记录 ...
- Python 入门之 内置模块 -- re模块
Python 入门之 内置模块 -- re模块 1.re 模块 (1)什么是正则? 正则就是用一些具有特殊含义的符号组合到一起(称为正则表达式)来描述字符或者字符串的方法.或者说:正则就是用来描述一类 ...
- Python 入门之 内置模块 -- collections模块
Python 入门之 内置模块 -- collections模块 1.collections -- 基于Python自带的数据类型之上额外增加的几个数据类型 from collections 在内 ...
- Python 入门之 内置模块 -- hashlib模块
Python 入门之 内置模块 -- hashlib模块 1.hashlib 摘要算法,加密算法 (1)主要用途: <1> 加密 : md5 sha1 sha256 sha512 md5, ...
- Python 入门之 内置模块 -- sys模块
Python 入门之 内置模块 -- sys模块 1.sys模块 sys模块是与python解释器交互的一个接口 print(sys.path) #模块查找的顺序 print(sys.argv) # ...
- Python 入门之 内置模块 -- os模块
Python 入门之 内置模块 -- os模块 1.os os是和操作系统做交互,给操作发指令 os模块是与操作系统交互的一个接口,它提供的功能多与工作目录,路径,文件等相关 (1)工作路径 prin ...
- Python 入门之 内置模块 -- 序列化模块(json模块、pickle模块)
Python 入门之 内置模块 -- 序列化模块(json模块.pickle模块) 1.序列化 Python中这种序列化模块有三种: json模块 : 不同语言都遵循的一种数据转化格式,即不同 ...
随机推荐
- shell中信号处理
参考: Shell 脚本中信号处理实践 Linux Shell 的信号 trap 功能你必须知道的细节 在 unix 里,可能发生的每一种类型的事件都是由一个独立的信号来描述,每一个信号都是一个小 ...
- MVC插件
MVC插件 最近领导让我搞一下插件化,就是实现多个web工程通过配置文件进行组装.之前由于做过一个简单的算是有点经验,当时使用的不是area,后来通过翻看orchard源码有点启发,打算使用area改 ...
- 025 Spark中的广播变量原理以及测试(共享变量是spark中第二个抽象)
一:来源 1.说明 为啥要有这个广播变量呢. 一些常亮在Driver中定义,然后Task在Executor上执行. 如果,有多个任务在执行,每个任务需要,就会造成浪费. 二:共享变量的官网 1.官网 ...
- Harbor 企业级镜像仓库搭建
Habor是由VMWare公司开源的容器镜像仓库.事实上,Habor是在Docker Registry上进行了相应的 企业级扩展,从而获得了更加广泛的应用,这些新的企业级特性包括:管理用户界面,基于角 ...
- webpack4.x打包配置
很长时间没有进行webpack打包配置了,想起来都快有些忘记了,这个东西不是经常用到,只有在新建个项目的时候用到,不用官方模板,自己去动手配置的时候,有时候觉得还是有点难度.今天就想着自己动手进行配置 ...
- Ubuntu下登陆远程postgresql数据库
登陆公司远程postgresql:psql -h <host or remote id> -p <port> dbdame 如: psql -h aliyunsql_addr ...
- 压缩归档文件审查工具p7zip-full
压缩归档文件审查工具p7zip-full 在数字取证中,会遇到各种形式的压缩文件和归档文件.为了处理这些不同的文件,Kali Linux提供了专用工具p7zip-full.该工具支持各种格式的压缩 ...
- 21.python中的闭包和装饰器
python中的闭包从表现形式上定义(解释)为:如果在一个内部函数里,对在外部作用域(但不是在全局作用域)的变量进行引用,那么内部函数就被认为是闭包(closure). 以下说明主要针对 python ...
- spring-boot 速成(4) 自定义配置
spring-boot 提供了很多默认的配置项,但是开发过程中,总会有一些业务自己的配置项,下面示例了,如何添加一个自定义的配置: 一.写一个自定义配置的类 package com.example.c ...
- Ubuntu Java7 SDK环境变量配置(转)
1.去甲骨文官网下载java7 sdk http://www.oracle.com/technetwork/java/javase/downloads/index.html 这里笔者下载了最新的jav ...