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模块 : 不同语言都遵循的一种数据转化格式,即不同 ...
随机推荐
- 记2013年度成都MVP社区巡讲
上个周六在天府软件园A区的翼起来咖啡举行了MVP社区巡讲成都站的活动,这个巡讲活动去年也搞过一次. MVP社区巡讲是 @微软中国MVP项目组 支持的,由各地的MVP担任讲师,给本地技术社区提供的一种社 ...
- df -h命令卡死解决办法
1.现象 同事突然反应说有个服务器进入/目录运行 ls -l 无反应,同时运行df -h也卡死了.如果你的机器有用到nfs请直接看第四大点. 2.分析 运行mount [conversant@sw ...
- php 会话控制(Session会话控制)
php的session会话是通过唯一的会话ID来驱动的,会话ID是一个加密的随机数字,由php生成,在会话的生命周期中都会保存在客户端.客户端保存数据的地方只有cookie,所以php的会话ID一般保 ...
- 基于图文界面的蓝牙扫描工具btscanner
基于图文界面的蓝牙扫描工具btscanner btscanner是Kali Linux内置的一款蓝牙扫描工具.它提供图文界面,更便于渗透测试人员查看扫描信息.该工具会自动使用主机所有的蓝牙接口,并 ...
- IE9中ajax请求成功后返回值却是undefined
ie9中ajax请求一般处理程序成功后返回值始终是undefined,在网上找过很多资料,大致意思都是说前后端编码不一致造成的,但是按照资料上的方案去修改却发现根本不能解决我的问题,试过好多种方案都不 ...
- Intel Code Challenge Elimination Round (Div.1 + Div.2, combined) D. Generating Sets 贪心
D. Generating Sets 题目连接: http://codeforces.com/contest/722/problem/D Description You are given a set ...
- Markdown,你只需要掌握这几个
目录 题记 正文 1. 常用标记 这是一级标题 这是二级标题 这是三级标题 这是高阶标题(效果和一级标题一样 ) 这是次阶标题(效果和二级标题一样) 2. 次常用标记 3. 不常用标记 4. 专项使用 ...
- vue项目开发之v-for列表渲染的坑
不知道大家在用vue开发的过程中有没有遇到过在使用v-for的时候会出现大片的黄色警告,比如下图: 其实这是因为没有写key的原因 :key是为vue的响应式渲染提供方法,在列表中单条数据改变的情况下 ...
- 无线端安全登录与鉴权一之Kerberos
无线端登录与鉴权是安全登录以及保证用户数据安全的第一步,也是最重要的一步.之前做过一个安全登录与鉴权的方案,借这个机会,系统的思考一下,与大家交流交流 先介绍一下TX系统使用的Kerberos方案,参 ...
- 微信小程序自定义音频组件,自定义滚动条,单曲循环,循环播放
小程序自定义音频组件,带滚动条 摘要:首先自定义音频组件,是因为产品有这样的需求,需要如下样式的 而微信小程序API给我们提供的就是这样的 而且产品需要小程序有后台播放功能,所以我们不考虑小程序的 a ...