psycopg2接口的基本用法

轉載自: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()
(1100, “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(20102814027425337)
 
>>> 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’;”

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章