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()
( 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’;”

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值