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模块 : 不同语言都遵循的一种数据转化格式,即不同 ...
随机推荐
- Linux 正则
一.引用自:https://www.cnblogs.com/chensiqiqi/p/6285060.html 二.grep示例 grep -i 忽略大小写 grep -w 精准匹配 grep - ...
- 013 jquery中关于表格行的增删问题
1.程序 <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <titl ...
- C语言中对数组名取地址
在C/C++中,数组名相当于一个指针,指向数组的首地址.这里“相当于”不代表等于,数组名和指针还是有很多区别的,这个在<C陷阱与缺陷>里有详尽的讲述.而这里要说的是对于数组名取地址的这么一 ...
- Python实现截图
本文主要介绍了Python实现截图的两种方式,使用PIL的方法和不使用PIL的方法.文中也涉及到了一些位图的知识.
- 004.SMB之guest级别配置
一 配置文件修改 注意: 1 share级别权限访问即,无任何验证共享,对guest开放. 2 新版samba4已取消share级别,可使用user级别配置成无验证共享. 1.1 全局配置文件修改 [ ...
- linux学习笔记-12.输入输出重定向及管道
1.新建一个文件 touch a.txt> b.txt 2.错误重定向:2> find /etc -name zhaoxing.txt 2> error.txt 3.将正确或错误的信 ...
- jquery 点击页面流畅弹出预定文字
js代码: <script src="https://cdn.bootcss.com/jquery/2.2.1/jquery.min.js"></script&g ...
- Android-Start方式和Bind方式混合开启Service
Android-Start方式和Bind方式混合开启Service 需求如下 需要开发一个音乐APP,需要满足以下的需求: 当退出所有的Activity后仍然能够播放音乐 能够控制音乐的播放比如说,暂 ...
- hdu 4407 容斥原理
题意: 1 //一组数据 3 3 //数字为1-3,3次运算 2 2 3 //将2号位变成3 1 1 3 4 //计算1-3号位上与4互质的数的和 1 2 3 6 好题,需要重复练习 #include ...
- 【斜优DP】bzoj4518-Sdoi2016征途
一.斜率优化DP与决策单调性 这里浅显(并且不严谨)地说明一下标题中的两个名词: 斜率优化DP:状态转移方程形如f[i]=min/max{f[k]+(x[i]-x[k])^y}的一类DP问题: 决策单 ...