通过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
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
相关文章推荐
- python 通过mysqldb 操作mysql数据库
- 第一个通过的ibatis操作mysql的实际例子
- Hadoop之——本地通过Eclipse链接Hadoop操作MySQL数据库问题小结
- [导入][原创]一个通过BackgroundWorker实现WinForm异步操作的例子
- linux 文件操作函数 通过例子来解释 父子间文件描述符共享 内存映像图
- JAVA操作SSL协议,通过Socket访问Https的程序代码例子
- C#操作MySQL数据库的简单例子
- Java中通过JDBC操作MySQL数据库
- Java学习笔记(十一)——通过JDBC操作mysql数据库
- 一个通过BackgroundWorker实现WinForm异步操作的例子
- Linux下通过C++码来操作MySQL数据库
- python操作三大主流数据库(1)python操作mysql①windows环境中安装python操作mysql数据库的MySQLdb模块mysql-client
- 本地通过Eclipse链接Hadoop操作Mysql数据库问题小结
- 二、JAVA通过JDBC连接mysql数据库(操作)
- MySQL数据库通过JDBC操作,简单查询
- Python操作MySQL数据库(二):MySQLdb模块
- Java通过JDBC 进行MySQL数据库操作
- 通过shell脚本操作mysql数据库
- Flex中通过doubleClick事件来检测用户是否在TextInput控件中进行了双击(double clicks)操作的例子
- C#操作MySQL数据库的简单例子