概述:
对于访问MySQL数据库的操作,我想大家也都有一些了解。不过,因为最近在学习Python,以下就用Python来实现它。其中包括创建数据库和数据表、插入记录、删除记录、修改记录数据、查询数据、删除数据表、删除数据库。还有一点就是我们最好使用一个新定义的类来处理这件事。因为这会使在以后的使用过程中更加的方便(只需要导入即可,避免了重复制造轮子)。

实现功能介绍:

1.封装一个DB类
2.数据库操作:创建数据库和数据表
3.数据库操作:插入记录
4.数据库操作:一次插入多条记录
5.数据库操作:删除记录
6.数据库操作:修改记录数据
7.数据库操作:一次修改多条记录数据
8.数据库操作:查询数据
9.数据库操作:删除数据表
10.数据库操作:删除数据库

数据库类的定义:
heroDB.py

#!/usr/bin/env python

import MySQLdb

DATABASE_NAME = 'hero'

class HeroDB:
    # init class and create a database
    def __init__(self, name, conn, cur):
        self.name = name
        self.conn = conn
        self.cur = cur
        try:
            cur.execute('create database if not exists ' + name)
            conn.select_db(name)
            conn.commit()
        except MySQLdb.Error, e:
            print "Mysql Error %d: %s" % (e.args[0], e.args[1])
                        
    # create a table
    def createTable(self, name):
        try:
            ex = self.cur.execute
            if ex('show tables') == 0:
                ex('create table ' + name + '(id int, name varchar(20), sex int, age int, info varchar(50))')
                self.conn.commit()
        except MySQLdb.Error, e:
            print "Mysql Error %d: %s" % (e.args[0], e.args[1])
            
    # insert single record
    def insert(self, name, value):
        try:
            self.cur.execute('insert into ' + name + ' values(%s,%s,%s,%s,%s)', value)
        except MySQLdb.Error, e:
            print "Mysql Error %d: %s" % (e.args[0], e.args[1])
            
    # insert more records
    def insertMore(self, name, values):
        try:
            self.cur.executemany('insert into ' + name + ' values(%s,%s,%s,%s,%s)', values)
        except MySQLdb.Error, e:
            print "Mysql Error %d: %s" % (e.args[0], e.args[1])
            
    # update single record from table
    # name: table name
    # values: waiting to update data
    def updateSingle(self, name, value):
        try:
            # self.cur.execute('update ' + name + ' set name=' + str(values[1]) + ', sex=' + str(values[2]) + ', age=' + str(values[3]) + ', info=' + str(values[4]) + ' where id=' + str(values[0]) + ';')
            self.cur.execute('update ' + name + ' set name=%s, sex=%s, age=%s, info=%s where id=%s;', value)
        except MySQLdb.Error, e:
            print "Mysql Error %d: %s" % (e.args[0], e.args[1])
            
    # update some record from table
    def update(self, name, values):
        try:
            self.cur.executemany('update ' + name + ' set name=%s, sex=%s, age=%s, info=%s where id=%s;', values)
        except MySQLdb.Error, e:
            print "Mysql Error %d: %s" % (e.args[0], e.args[1])
            
    # get record count from db table
    def getCount(self, name):
        try:
            count = self.cur.execute('select * from ' + name)
            return count
        except MySQLdb.Error, e:
            print "Mysql Error %d: %s" % (e.args[0], e.args[1])
            
    # select first record from database
    def selectFirst(self, name):
        try:
            self.cur.execute('select * from ' + name + ';')
            result = self.cur.fetchone()
            return result
        except MySQLdb.Error, e:
            print "Mysql Error %d: %s" % (e.args[0], e.args[1])
            
    # select last record from database
    def selectLast(self, name):
        try:
            self.cur.execute('SELECT * FROM ' + name + ' ORDER BY id DESC;')
            result = self.cur.fetchone()
            return result
        except MySQLdb.Error, e:
            print "Mysql Error %d: %s" % (e.args[0], e.args[1])
            
    # select next n records from database
    def selectNRecord(self, name, n):
        try:
            self.cur.execute('select * from ' + name + ';')
            results = self.cur.fetchmany(n)
            return results
        except MySQLdb.Error, e:
            print "Mysql Error %d: %s" % (e.args[0], e.args[1])
            
    # select all records
    def selectAll(self, name):
        try:
            self.cur.execute('select * from ' + name + ';')
            self.cur.scroll(0, mode='absolute') # reset cursor location (mode = absolute | relative)
            results = self.cur.fetchall()
            return results
        except MySQLdb.Error, e:
            print "Mysql Error %d: %s" % (e.args[0], e.args[1])
            
    # delete a record
    def deleteByID(self, name, id):
        try:
            self.cur.execute('delete from ' + name + ' where id=%s;', id)
        except MySQLdb.Error, e:
            print "Mysql Error %d: %s" % (e.args[0], e.args[1])
    
    # delete some record
    def deleteSome(self, name):
        pass
    
    # drop the table
    def dropTable(self, name):
        try:
            self.cur.execute('drop table ' + name + ';')
        except MySQLdb.Error, e:
            print "Mysql Error %d: %s" % (e.args[0], e.args[1])
            
    # drop the database
    def dropDB(self, name):
        try:
            self.cur.execute('drop database ' + name + ';')
        except MySQLdb.Error, e:
            print "Mysql Error %d: %s" % (e.args[0], e.args[1])
            
    def __del__(self):
        if self.cur != None:
            self.cur.close()
        if self.conn != None:
            self.conn.close()

使用范例:
testHeroDB.py

#!/usr/bin/env python

import MySQLdb
from heroDB import HeroDB

def main():
    conn = MySQLdb.connect(host='localhost', user='root', passwd='260606', db='hero', port=3306, charset='utf8')
    cur = conn.cursor()
    
    # ------------------------------------------- create -----------------------------------------------------
    hero = HeroDB('hero', conn, cur)
    hero.createTable('heros')
    
    # ------------------------------------------- insert -----------------------------------------------------
    hero.insert('heros', [3, 'Prophet', 0, 2000, 'The hero who in fairy tale.'])

# ------------------------------------------- select -----------------------------------------------------
    print '-' * 60
    print 'first record'
    result = hero.selectFirst('heros')
    print result
    
    print '-' * 60
    print 'last record'
    result = hero.selectLast('heros')
    print result
    
    print '-' * 60
    print 'more record'
    results = hero.selectNRecord('heros', 3)
    for item in results:
        print item
    
    print '-' * 60
    print 'all record'
    results = hero.selectAll('heros')
    for item in results:
        print item
        
    # ------------------------------------------- update -----------------------------------------------------
    hero.updateSingle('heros', ['Zeus', 1, 22000, 'The god.', 2])
    
    values = []
    values.append(['SunWukong', 1, 1300, 'The hero who in fairy tale.', 1])
    values.append(['Zeus', 1, 50000, 'The king who in The Quartet myth.', 2])
    values.append(['Prophet', 1, 20000, 'The hero who in fairy tale.3', 3])
    hero.update('heros', values)
    
    # ------------------------------------------- delete -----------------------------------------------------
    hero.deleteByID('heros', 1)
    
    hero.dropTable('heros')
    
    hero.dropDB('hero')
    
if __name__ == '__main__':
    main()

注:请不要不假思索地使用他们。如果你想实现某一个功能点,请最好将其他的功能点注释掉,这样才符合单元测试的规范。

Python访问MySQL数据库并实现其增删改查功能的更多相关文章

  1. Python操作MySQL数据库完成简易的增删改查功能

    说明:该篇博客是博主一字一码编写的,实属不易,请尊重原创,谢谢大家! 目录 一丶项目介绍 二丶效果展示 三丶数据准备 四丶代码实现 五丶完整代码 一丶项目介绍 1.叙述 博主闲暇之余花了10个小时写的 ...

  2. 关于利用PHP访问MySql数据库的逻辑操作以及增删改查实例操作

    PHP访问MySql数据库 <?php //造连接对象$db = new MySQLi("localhost","root","",& ...

  3. 使用JDBC分别利用Statement和PreparedStatement来对MySQL数据库进行简单的增删改查以及SQL注入的原理

    一.MySQL数据库的下载及安装 https://www.mysql.com/ 点击DOWNLOADS,拉到页面底部,找到MySQL Community(GPL)Downloads,点击 选择下图中的 ...

  4. MySQL数据库之表的增删改查

    目录 MySQL数据库之表的增删改查 1 引言 2 创建表 3 删除表 4 修改表 5 查看表 6 复制表 MySQL数据库之表的增删改查 1 引言 1.MySQL数据库中,数据库database就是 ...

  5. 在python中连接mysql数据库,并进行增删改查

    数据库在开发过程中是最常见的,基本上在服务端的编程过程中都会使用到,mysql是较常见的一种数据库,这里介绍python如果连接到数据库中,并对数据库进行增删改查. 安装mysql的python扩展 ...

  6. Mysql数据库和表的增删改查以及数据备份&恢复

    数据库 查看所有数据库 show databases; 使用数据库 use 数据库名; 查看当前使用的数据库 select database(); 创建数据库 create database 数据库名 ...

  7. Java连接MySQL数据库,并进行增删改查

    1.具体的代码实现 import java.sql.*; public class DatabaseService { /** * Create Connection * * @param dbtyp ...

  8. MySQL数据库 | 数据表的增删改查

    MySQL数据的增删改查(crud) 本文结构 一.增加 create 二.修改 update 三.查询 retrieve(简单查询,下篇详细展开) 四.删除 delete 首先,创建简单的class ...

  9. python3.6 使用 pymysql 连接 Mysql 数据库及 简单的增删改查操作

    1.通过 pip 安装 pymysql 进入 cmd  输入  pip install pymysql   回车等待安装完成: 安装完成后出现如图相关信息,表示安装成功. 2.测试连接 import ...

随机推荐

  1. VBA Promming入门教程——变量的使用

    数据类型 VBA中的数据类型可分为两种 示例 String Sub Main Dim s as string s = "Hello" msgbox(s) End Sub Singl ...

  2. 转行做web前端,该如何进行短期快速自学,达到高新就业水平

    就目前来说,毕业生如果想毕业就找到高薪的工作,互联网成为了第一个选择,在所有的职业中,不靠任何关系,全凭自己的能力就业,就是程序开发,而web前端开发是目最很热门的行业,在未来五年之内,web前端开发 ...

  3. 【转】C# WinForm中的Label如何换行

    第一种是把Label的AutoSize属性设为False,手动修改Label的大小.这样的好处是会因内容的长度而自动换行,但是当内容的长度超过所设定的大小时,多出的内容就会无法显示.因此,这种方法适合 ...

  4. Warning: date(): It is not safe to rely on the system's timezone settings. You are *required* to use ...报错

    错误截图 Warning: date(): It is not safe to rely on the system's timezone settings. You are *required* t ...

  5. tab bar controller

    下面记一下怎样通过代码的方式为选项卡添加视图. 1.创建一个基于Empty Application的项目 2.创建两个新类,基类选择UIViewController,勾选With XIB for us ...

  6. xcode菜单栏

    File  文件 Edit  编辑 View 视图 Navigate 导航 Editor 编辑 Product 产品 Window  窗口 Help 帮助 File  文件 New 新建        ...

  7. 【详●析】[GXOI/GZOI2019]逼死强迫症

    [详●析][GXOI/GZOI2019]逼死强迫症 脑子不够用了... [题目大意] 在\(2\times N\)的方格中用\(N-1\)块\(2\times 1\)的方砖和\(2\)块\(1\tim ...

  8. MySQL丨03丨基本语句

    MySQL语句都是以 ; 号结尾的 看库(刘大婶直接面对的是各种档案袋) show databases; 建库(新弄了一个档案袋) create database database_name; 删库( ...

  9. mysql alter修改数据库表结构用法

    1.alter操作表字段 (1)增加字段 alter table 表名 add 字段名 字段类型: alter table student add name varchar(10): (2)修改字段 ...

  10. Linux内核学习总览

    断断续续学习操作系统已经有大半年时间了,一直想系统地梳理一下. 正好借助<深入Linux内核架构> (Wolfgang Manuere 著,郭旭 译)汇总一下. 首先基础框架篇,Linux ...