python使用MySQLdb访问mysql数据库的方法

yipeiwu_com5年前Python基础

本文实例讲述了python使用MySQLdb访问mysql数据库的方法。分享给大家供大家参考。具体如下:

#!/usr/bin/python
import MySQLdb
def doInsert(cursor,db):
 #insert
 # Prepare SQL query to INSERT a record into the database.
 sql = "UPDATE EMPLOYEE SET AGE = AGE+1 WHERE SEX = '%c'" %('M')
 try:
  cursor.execute(sql)
  db.commit()
 except:
  db.rollback()
def do_query(cursor,db):
 sql = "SELECT * FROM EMPLOYEE \
     WHERE INCOME > '%d'" % (1000)
 try:
   # Execute the SQL command
   cursor.execute(sql)
   # Fetch all the rows in a list of lists.
   results = cursor.fetchall()
   print 'resuts',cursor.rowcount
   for row in results:
    fname = row[0]
    lname = row[1]
    age = row[2]
    sex = row[3]
    income = row[4]
    # Now print fetched result
    print "fname=%s,lname=%s,age=%d,sex=%s,income=%d" % \
        (fname, lname, age, sex, income )
 except:
   print "Error: unable to fecth data"
def do_delete(cursor,db):
 sql = 'DELETE FROM EMPLOYEE WHERE AGE > {}'.format(20)
 try:
  cursor.execute(sql)
  db.commit()
 except:
  db.rollback()
def do_insert(cursor,db,firstname,lastname,age,sex,income):
 sql = "INSERT INTO EMPLOYEE(FIRST_NAME, \
    LAST_NAME, AGE, SEX, INCOME) \
    VALUES ('%s', '%s', '%d', '%c', '%d' )" % \
    (firstname,lastname,age,sex,income)
 try:
  cursor.execute(sql)
  db.commit()
 except:
  db.rollback()
# Open database connection
# change this to your mysql account
#connect(server,username,password,db_name)
db = MySQLdb.connect("localhost","hunter","hunter","pydb" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
do_query(cursor,db)
doInsert(cursor,db)
do_query(cursor,db)
do_delete(cursor,db)
do_query(cursor,db)
do_insert(cursor,db,'hunter','xue',22,'M',2000)
do_insert(cursor,db,'mary','yang',22,'f',5555)
do_insert(cursor,db,'zhang','xue',32,'M',5000)
do_insert(cursor,db,'hunter','xue',22,'M',333)
do_query(cursor,db)
# disconnect from server
db.close()

希望本文所述对大家的Python程序设计有所帮助。

相关文章

python插入排序算法实例分析

本文实例讲述了python插入排序算法。分享给大家供大家参考。具体如下: def insertsort(array): for removed_index in range(1...

5款非常棒的Python工具

5款非常棒的Python工具

工欲善其事必先利其器,一个好的工具能让起到事半功倍的效果,Python社区提供了足够多的优秀工具来帮助开发者更方便的实现某些想法,下面这几个工具给我的工作也带来了很多便利,推荐给追求美好...

Python CSV文件模块的使用案例分析

Python CSV文件模块的使用案例分析

本文实例讲述了Python CSV文件模块的使用。分享给大家供大家参考,具体如下: 1、CSV模块使用流程 1、导入模块 impport CSV 2、打开文件(xxx.csv)...

TensorFlow基于MNIST数据集实现车牌识别(初步演示版)

TensorFlow基于MNIST数据集实现车牌识别(初步演示版)

在前几天写的一篇博文《如何从TensorFlow的mnist数据集导出手写体数字图片》中,我们介绍了如何通过TensorFlow将mnist手写体数字集导出到本地保存为bmp文件。 车牌...

Window环境下Scrapy开发环境搭建

Window环境下Scrapy开发环境搭建

快速搭建scrapy开发环境 python pippip 百度网盘 注:不同的电脑上所带有环境不同,安装方式有些许差别 1、成功安装python并添加环境变量 2、安装...