转载自:http://zhiwei.li/text/2012/02/05/psycopg2接口的基本用法/
与其他实现了DB API 2.0协议的其他数据库用户基本一致。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
import
psycopg2
##连接到一个存在的数据库
conn
=
psycopg2.connect(“dbname
=
test user
=
postgres”)
##connect()建立一个新的数据库会话,并返回一个connect实例
##打开一个光标,用来执行数据库操作
cur
=
conn.cursor()
##执行命令:建立一个新表
cur.execute(“CREATE TABLE test (
id
serial PRIMARY KEY, num integer, data varchar);”)
##传递数据用来填充查询占位符, 让Psycopg执行正确的转换(不再有SQL注入)
cur.execute(“INSERT INTO test (num, data) VALUES (
'%s'
,
'%s'
);”
%
(
100
, “abc’
def
”))
##查询数据库,取得数据作为python对象
cur.execute(“SELECT
*
FROM test;”)
cur.fetchone()
(
1
,
100
, “abc’
def
”)
##使改变永久存入数据库
conn.commit()
##关闭到数据库的通信
cur.close()
conn.close()
|
python数据类型到SQL类型的适配
日期和时间对象: python内建的datetime, date, time, timedelta 被转换成 PostgreSQL的 timestamp, date, time, interval 数据类型. Time zones are supported too. The Egenix mx.DateTime objects are adapted the same way:
1
2
3
4
5
6
7
|
>>> dt
=
datetime.datetime.now()
>>> dt datetime.datetime(
2010
,
2
,
8
,
1
,
40
,
27
,
425337
)
>>> cur.mogrify(“SELECT
%
s,
%
s,
%
s;”, (dt, dt.date(), dt.time())) “SELECT ‘
2010
-
02
-
08T01
:
40
:
27.425337
’, ‘
2010
-
02
-
08
′, ’
01
:
40
:
27.425337
′;”
>>> cur.mogrify(“SELECT
%
s;”, (dt – datetime.datetime(
2010
,
1
,
1
),)) “SELECT ’
38
days
6027.425337
seconds’;”
|