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

本文提供了一个使用 Python 和 MySQLdb 库进行数据库增删改查(CRUD)操作的完整示例程序。通过此示例,读者可以了解如何连接 MySQL 数据库、执行 SQL 语句以插入、更新数据及查询并打印结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

例子程序:

  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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值