python中MySQLdb模块用法实例

2019-10-05 13:43:52王旭

try:
   # 执行sql语句
   cursor.execute(sql)
   # 提交到数据库执行
   db.commit()
except:
   # 发生错误时回滚
   db.rollback()
# 关闭数据库连接
db.close()
也可以以变量的方式传递参数,如下:
..................................
user_id = "test"
password = "password123"
con.execute('insert into Login values("%s", "%s")' %
             (user_id, password))
..................................
3、数据库查询操作
以查询EMPLOYEE表中salary(工资)字段大于1000的所有数据为例:
#!/usr/bin/python
# encoding: utf-8
import MySQLdb
# 打开数据库连接
db = MySQLdb.connect("localhost","root","361way","test" )
# 使用cursor()方法获取操作游标
cursor = db.cursor()
# SQL 查询语句
sql = "SELECT * FROM EMPLOYEE
       WHERE INCOME > '%d'" % (1000)
try:
   # 执行SQL语句
   cursor.execute(sql)
   # 获取所有记录列表
   results = cursor.fetchall()
   for row in results:
      fname = row[0]
      lname = row[1]
      age = row[2]
      sex = row[3]
      income = row[4]
      # 打印结果
      print "fname=%s,lname=%s,age=%d,sex=%s,income=%d" %
             (fname, lname, age, sex, income )
except:
   print "Error: unable to fecth data"
# 关闭数据库连接
db.close()
以上脚本执行结果如下:
fname=Mac, lname=Mohan, age=20, sex=M, income=2000

4、数据库更新操作
更新操作用于更新数据表的的数据,以下实例将 test表中的 SEX 字段全部修改为 'M',AGE 字段递增1:
# encoding: utf-8
#!/usr/bin/python
import MySQLdb
# 打开数据库连接
db = MySQLdb.connect("localhost","root","361way","test" )
# 使用cursor()方法获取操作游标
cursor = db.cursor()
# SQL 更新语句
sql = "UPDATE EMPLOYEE SET AGE = AGE + 1
                          WHERE SEX = '%c'" % ('M')
try:
   # 执行SQL语句
   cursor.execute(sql)
   # 提交到数据库执行
   db.commit()
except:
   # 发生错误时回滚
   db.rollback()
# 关闭数据库连接