概述:
对于访问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. 完整卸载MySQL数据库

    1. 关掉mysql服务 右键“我的电脑”,选择“管理”,打开计算机管理,选择“服务” 右键MySQL服务,选择“停止” 2. 卸载mysql程序 开始菜单->控制面板->程序和功能 3. ...

  2. (10) openssl dhparam(密钥交换)

    openssl dhparam用于生成和管理dh文件.dh(Diffie-Hellman)是著名的密钥交换协议,或称为密钥协商协议,它可以保证通信双方安全地交换密钥. 但注意,它不是加密算法,所以不提 ...

  3. Linux test命令

    test命令 长格式的例子: test "$A" == "$B" && echo "Strings are equal" t ...

  4. 使用js获取页面的各种高度

    使用js获取相关高度: 获取网页被滚动条卷去的高度——兼容写法: scrollHeight = documen.body.scrollTop || document.documentElement.s ...

  5. pwnable.kr cmd2之write up

    来看一下源代码: #include <stdio.h> #include <string.h> int filter(char* cmd){ ; r += strstr(cmd ...

  6. 【BZOJ 3555】 [Ctsc2014]企鹅QQ(哈希)

    Description PenguinQQ是中国最大.最具影响力的SNS(Social Networking Services)网站,以实名制为基础,为用户提供日志.群.即时通讯.相册.集市等丰富强大 ...

  7. POJ 1414 Life Line(搜索)

    题意: 给定一块正三角形棋盘,然后给定一些棋子和空位,棋子序号为a(1<=a<=9),group的定义是相邻序号一样的棋子. 然后到C(1<=N<=9)棋手在空位放上自己序号C ...

  8. unittest多线程生成报告(BeautifulReport)

    前言 selenium多线程跑用例,这个前面一篇已经解决了,如何生成一个测试报告这个是难点,刚好在github上有个大神分享了BeautifulReport,完美的结合起来,就能生成报告了. 环境必备 ...

  9. [luoguP1273] 有线电视网(DP)

    传送门 f[i][j]表示节点i选j个用户的最大收益 #include <cstdio> #include <cstring> #include <iostream> ...

  10. Linux(5):正则表达式 & 权限

    正则表达式: 特殊符号: '' ---> 所见即所得,里面的内容都会被原封不动的输出出来 "" ---> 与单引号类似,但其中的特殊符号会被解析运行 `` ---> ...