用于python 3的postgresql数据库适配器
pgsql的Python项目详细描述
- 重量轻
- 完全用python编写
- 无外部依赖关系
- 非线程安全
安装
$ pip install pgsql
示例
importpgsql# address defaults to ("localhost", 5432), a string must point to a unix socket# user defaults to "postgres"# password defaults to None# database equals user by defaultdb=pgsql.Connection(user="antti",database="postgres")print(db("CREATE TABLE people (name TEXT, age INT)"))print(db("INSERT INTO people (name, age) VALUES ($1, $2)","Veronica",18))print(db("SELECT * FROM people"))db.close()# for convenience, connection objects support the with statementwithpgsql.Connection(user="antti",database="postgres")asdb:# you can use .begin(), .commit(), .rollback() manually, or use the with statementwithdb.transaction():withdb.prepare("INSERT INTO people (name, age) VALUES ($1, $2)")asps:forpersonin("Wallace",18),("Keith",45),("Lianne",44):ps(*person)# iterate through and print all the rows represented as tuplespeople=db.prepare("SELECT * FROM people")forpersoninpeople():print(person)# sometimes instead of an iterator, you want the rows as a list# you may also want to call columns by their namepeople_over=db.prepare("SELECT * FROM people WHERE age > $1").allforpersoninpeople_over(21):print(person.name,"is",person.age-21,"years over the age of 21")# when the expected result is only one row, it's convenient to call .firstperson_named=db.prepare("SELECT * FROM people WHERE name = $1 LIMIT 1").firstprint(person_named("Veronica"))print(person_named("Backup"))
打印
[] [] [('Veronica', 18)] ('Veronica', 18) ('Wallace', 18) ('Keith', 45) ('Lianne', 44) Keith is 24 years over the age of 21 Lianne is 23 years over the age of 21 ('Veronica', 18) None
更改
1.1(2014-03-26)
- 通过调用Connectionobject可以执行一次性语句