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+selenium实现自动循环扔QQ邮箱漂流瓶

本文实例为大家分享了Python自动循环扔QQ邮箱漂流瓶的具体代码,供大家参考,具体内容如下 Python代码如下: # coding=utf-8 from selenium imp...

Window环境下Scrapy开发环境搭建

Window环境下Scrapy开发环境搭建

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

PyQtGraph在pyqt中的应用及安装过程

PyQtGraph在pyqt中的应用及安装过程

1.PyQtGraph简介: pyqtgraph的主要用途: 1、为数据、绘图、视频等提供快速、可交互图形显示。 2、提供快速开发应用的工具。 2.PyQtGraph的安装: pip i...

Python的Flask框架中Flask-Admin库的简单入门指引

Python的Flask框架中Flask-Admin库的简单入门指引

 Flask-Admin是一个功能齐全、简单易用的Flask扩展,让你可以为Flask应用程序增加管理界面。它受django-admin包的影响,但用这样一种方式实现,开发者拥...

Python中__new__与__init__方法的区别详解

在python2.x中,从object继承得来的类称为新式类(如class A(object))不从object继承得来的类称为经典类(如class A()) 新式类跟经典类的差别主要是...