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

yipeiwu_com6年前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 使用pdfminer3k 读取PDF文档的例子

python 使用pdfminer3k 读取PDF文档的例子

1、安装 pdfminer3k 通过pip安装: pip install pdfminer3k 下载安装:在网页 https://pypi.org/project/pdfminer3k/...

python中将两组数据放在一起按照某一固定顺序shuffle的实例

有的时候需要将两组数据,比如特征和标签放在一起随机打乱, 但是又想记录这种打乱的顺序,那么该怎么做呢?下面是一个很好的方法: b = [1, 2,3, 4, 5,6 , 7,8 ,9...

Python实现包含min函数的栈

本文实例讲述了Python实现包含min函数的栈。分享给大家供大家参考,具体如下: # coding=utf8 ''' 题目:定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元...

Python编程实现微信企业号文本消息推送功能示例

本文实例讲述了Python微信企业号文本消息推送功能。分享给大家供大家参考,具体如下: 企业号的创建、企业号应用的创建、组、tag、part就不赘述了,一搜一大堆,但是网上拿的那些个脚本...

git使用.gitignore设置不生效或不起作用问题的解决方法

偶然遇到的问题,记录如下: 通常我们在push项目时,会有些配置文件或本地文件不想上传到服务器上 这时候我们会通过设置.gitignore  文件 一般设置成这样: ###...