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返回真假值(True or False)小技巧

Python返回真假值(True or False)小技巧

在昨天关于substring的blog中有如下一段代码: 也许你已经发现,在Python 3中其实有办法只用一行完成函数: 复制代码 代码如下: >>> def is...

Python实现检测文件MD5值的方法示例

本文实例讲述了Python实现检测文件MD5值的方法。分享给大家供大家参考,具体如下: 前面介绍过Python计算文件md5值的方法,这里分析一下Python检测文件MD5值的另一种实现...

python3 pygame实现接小球游戏

python3 pygame实现接小球游戏

本文实例为大家分享了python3 pygame接小球游戏的具体代码,供大家参考,具体内容如下 操作方法:鼠标操作 截图: 直接放代码: # -*- coding:utf-8 -...

Django数据库操作的实例(增删改查)

创建数据库中的一个表 class Business(models.Model): #自动创建ID列 caption = models.CharField(max_length=3...

Python统计文件中去重后uuid个数的方法

本文实例讲述了Python统计文件中去重后uuid个数的方法。分享给大家供大家参考。具体如下: 利用正则表达式按行获取日志文件中的的uuid,并且统计这些uuid的去重个数(去重利用se...