您的位置:首页 > 编程语言 > Python开发

通过pythong MySQLdb操作mysql数据库的例子

2010-11-10 16:14 302 查看
例子程序:

1 import os, sys

2 import MySQLdb

#先连接数据库,获得conn对象

3 try:

4 conn = MySQLdb.connect(host='10.1.166.132',user='root',passwd='nothing',db='tm')

5 except Exception, e:

6 print e

7 sys.exit()

#获得cursor,用cursor的方法来操作数据

8 cursor = conn.cursor()

#插入一条数据

9 sql1 = "insert into user values(4,'sheldon','nothing','mobile')"

10 n = cursor.execute(sql1)#n是操作影响的记录数

11 print "n =%d"% n

#修改一条记录

12 updatesql = "update user set username = 'haha2' where Id =2;"

13 n = cursor.execute(updatesql)

14 print "n =%d"% n

15 conn.commit()#此处必须commit才能把上面的数据库操作写到数据库里面

#选择数据,并print

16 sql = "select * from user;"

17 n = cursor.execute(sql)

18 alldata = cursor.fetchall()

19 if alldata:

20 for rec in alldata:

21 print rec[0], rec[1],rec[2],rec[3]

#最后要把cursor和conn对象close,断开与数据库的连接.

22 cursor.close()

23 conn.close()

执行结果:

[root@localhost testcase]# python test.py

n =1

n =1

1 frank nothing mobile

2 haha2 nothing mobile

3 jack nothing mobile

4 sheldon nothing mobile
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: