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模块 : 不同语言都遵循的一种数据转化格式,即不同 ...
随机推荐
- HNOI2019滚粗记
HNOI2019滚粗记 标签: 游记 Day -1 在学校打摆被抓. Day 0 在家打摆. Day 1 来长沙理工大学打摆 开场看完题之后,感觉T3不太可做,然后T1T2又显得特别套路,然后把T2 ...
- Serilog 记录日志
Serilog 记录日志 Serilog是.net里面非常不错的记录日志的库,另外一个我认为比较好的Log库是NLog. 在我个人的asp.net web api 2 基础框架(Github地址)里, ...
- NET Core中使用Angular2的Token base身份认证
下载本文提到的完整代码示例请访问:How to authorization Angular 2 app with asp.net core web api 在ASP.NET Core中使用Angula ...
- redis 使用管道提升写入的性能[pipeline]
看了手册的都知道multi这个命令的作用就好比是mysql的事务的功能,但是大家都知道事务吗,就是在操作的过程中,把整个操作当作一个原子来处理,避免由于中途出错而导致最后产生的数据不一致,而产生BUG ...
- html (第四本书第1~3章参考)
前三章都不会的话 呵呵……
- zoj 3640 概率dp
题意:一只吸血鬼,有n条路给他走,每次他随机走一条路,每条路有个限制,如果当时这个吸血鬼的攻击力大于等于某个值,那么就会花费t天逃出去,否则,花费1天的时间,并且攻击力增加,问他逃出去的期望 用记忆化 ...
- Linux——线程
线程 我们都知道一个程序的执行是由进程来完成的,而进程里真正执行代码却是由线程来完成,它是真正的执行流.通常将一个程序⾥里一个执行路线就叫做线程(thread).对它更准确的定义是:线程是“一个进程内 ...
- shell 常用命令语句
查找并删除 sudo fing / -name '*fcitx*' | xargs sudo rm -rf find . -type d -name ‘.svn’ | xargs rm -rf fin ...
- linearLayout 和 relativeLayout的属性区别(转)
LinearLayout和RelativeLayout 共有属性:java代码中通过btn1关联次控件android:id="@+id/btn1" 控件宽度android:layo ...
- oracle sql 高级
1 时间 如果是从当前时间到前一个月的这个时候之间的记录总条数: select count(1) from uis_md_stcustom u where firsttime betw ...