支持SQL标准的可用数据库有很多,其中多数在Python中都有对应的客户端模块.
这里我使用的mysql,它需要安装MySQLdb包.它相当于Python的数据接口规范Python DB API.
1 |
root @10 .1. 1.45 :~#
apt-get install python-mysqldb |
2 |
root @10 .1. 1.45 :~#
python |
3 |
Python 2.5 . 2 (r252: 60911 ,
Jan 4 2009 , 21 : 59 : 32 ) |
5 |
Type "help" , "copyright" , "credits" or "license" for more
information. |
这里导入MySQLdb没有报错,就说明安装成功.
下面就可以连接数据库,可以进行增删改操作.
01 |
root @10 .1. 1.45 :python#
cat create.py |
09 |
conn
= MySQLdb.connect(host= 'localhost' ,user= 'root' ,passwd= 'davehe' ) |
13 |
curs.execute( "create
database pythondb" ) |
15 |
conn.select_db( 'pythondb' ) |
17 |
curs.execute( "create
table test(id int,message varchar(50))" ) |
20 |
curs.execute( "insert
into test values(%s,%s)" ,value) |
24 |
values.append((i, 'hello
mysqldb' +
str(i))) |
25 |
curs.executemany( "insert
into test values(%s,%s)" ,values) |
32 |
root @10 .1. 1.45 :python#
./create.py |
下面利用python查看mysql里刚添加的记录.
01 |
root @10 .1. 1.45 :python#
cat select.py |
09 |
conn
= MySQLdb.connect(host= 'localhost' ,user= 'root' ,passwd= 'hc1226' ) |
13 |
conn.select_db( 'pythondb' ) |
15 |
count
= curs.execute( 'select
* from test' ) |
16 |
print "一共有%s条记录" %
count |
18 |
result
= curs.fetchone() |
19 |
print "当前的一条记录
ID:%s message:%s" %
result |
20 |
#获取后 10 条记录,由于之前执行了getchone(),所以游标已经指到第二条记录,下面也就从第二条记录开始返回 |
21 |
results
= curs.fetchmany( 10 ) |
24 |
#重置游标位置, 0 ,为偏移量,mode
= relative(默认) |
25 |
curs.scroll( 0 ,mode= 'absolute' ) |
27 |
results
= curs.fetchall() |
01 |
root @10 .1. 1.45 :python#
./select.py |
03 |
当前的一条记录
ID: 1 message:davehe |
04 |
(0L, 'hello
mysqldb0' ) |
05 |
(1L, 'hello
mysqldb1' ) |
06 |
(2L, 'hello
mysqldb2' ) |
07 |
(3L, 'hello
mysqldb3' ) |
08 |
(4L, 'hello
mysqldb4' ) |
09 |
(5L, 'hello
mysqldb5' ) |
10 |
(6L, 'hello
mysqldb6' ) |
11 |
(7L, 'hello
mysqldb7' ) |
12 |
(8L, 'hello
mysqldb8' ) |
13 |
(9L, 'hello
mysqldb9' ) |
15 |
(0L, 'hello
mysqldb0' ) |
16 |
(1L, 'hello
mysqldb1' ) |
17 |
(2L, 'hello
mysqldb2' ) |
18 |
(3L, 'hello
mysqldb3' ) |
19 |
(4L, 'hello
mysqldb4' ) |
20 |
(5L, 'hello
mysqldb5' ) |
21 |
(6L, 'hello
mysqldb6' ) |
22 |
(7L, 'hello
mysqldb7' ) |
23 |
(8L, 'hello
mysqldb8' ) |
24 |
(9L, 'hello
mysqldb9' ) |
25 |
(10L, 'hello
mysqldb10' ) |
26 |
(11L, 'hello
mysqldb11' ) |
27 |
(12L, 'hello
mysqldb12' ) |
28 |
(13L, 'hello
mysqldb13' ) |
29 |
(14L, 'hello
mysqldb14' ) |
30 |
(15L, 'hello
mysqldb15' ) |
31 |
(16L, 'hello
mysqldb16' ) |
32 |
(17L, 'hello
mysqldb17' ) |
33 |
(18L, 'hello
mysqldb18' ) |
34 |
(19L, 'hello
mysqldb19' ) |
附:
connect函数的常用参数
user #用户名
password #用户密码
host #主机名
database #数据库名
connect函数会返回连接对象,连接对象方法
close() #关闭连接之后,连接对象和它的游标均不可用
commit() #如果支持的话就提交挂起的事务,否则不做任何事
rollback() #回滚挂起的事务(可能不可用)
cursor() #返回连接的游标对象
游标对象方法
close() #关闭游标
execute(oper[,params]) #执行SQL操作,可能使用参数
executemany(oper,pseq) #对序列中的每个参数执行SQL操作
fetchone() #把查询的结果集中的下一行保存为序列,或者None
fetchmany([size]) #获取查询结果集中的多行,默认为1
fetchall() #将所有(剩余)的行作为序列的序列