——简单整理翻译自官方文档: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.
Contents