Python访问MySQL数据库并实现其增删改查功能

概述:

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

实现功能介绍:

1.封装一个DB类

2.数据库操作:创建数据库和数据表

3.数据库操作:插入记录

4.数据库操作:删除记录

5.数据库操作:修改记录数据

6.数据库操作:查询数据

7.数据库操作:删除数据表

8.数据库操作:删除数据库

数据库类的定义:

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()

源码下载:

http://download.csdn.net/detail/u013761665/8615981

时间: 2024-08-28 23:38:16

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

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

PHP访问MySql数据库 <?php //造连接对象$db = new MySQLi("localhost","root","","0710_test"); //写SQL语句$sql = "select * from student";//检测连接数据库是否成功,失败返回"连接失败",并退出程序 if(mysqli_connect_error()){    die("连

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

一.MySQL数据库的下载及安装 https://www.mysql.com/ 点击DOWNLOADS,拉到页面底部,找到MySQL Community(GPL)Downloads,点击 选择下图中的MySQL Community Server 选择想要的版本进行下载 之后的步骤,因为本人已经安装过MySQL数据库,而卸载重装会比较麻烦,卸载不干净会导致新的装不上,所以可以参考下面的博客,因为官网的改动,前面的部分已经与该博客不符,按照本人在上面的介绍寻找即可 https://blog.csdn

MySQL数据库之表的增删改查

目录 MySQL数据库之表的增删改查 1 引言 2 创建表 3 删除表 4 修改表 5 查看表 6 复制表 MySQL数据库之表的增删改查 1 引言 1.MySQL数据库中,数据库database就是硬盘上的一个文件夹,表table就是文件夹里面的一个文件 2.表中的一条记录就相当于文件中的一行内容,与excel表类似,表table中有不同的标题,称之为字段 3.本节对表结构做增删改查,即创建表.删除表.修改表.查看表结构,至于表中数据的增删改查日后单独总结 2 创建表 1.创建一张表,需要建一

java H2数据库使用并实现增删改查功能

原文:java H2数据库使用并实现增删改查功能 代码下载地址:http://www.zuidaima.com/share/1550463278058496.htm package com.zuidaima.h2sql.test; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.St

mysql数据库的连接以及增删改查Java代码实现(PreparedStatement版)

数据库: create table t1(id int primary key not null auto_increment,name varchar(32),password varchar(32)); insert into t1(name,password) values('admin','123'); insert into t1(name,password) values('zhangsan','123'); insert into t1(name,password) values(

mysql数据库的连接以及增删改查Java代码实现(Statement版)

数据库: create table t1(id int primary key not null auto_increment,name varchar(32),password varchar(32)); insert into t1(name,password) values('admin','123'); insert into t1(name,password) values('zhangsan','123'); insert into t1(name,password) values(

JAVA 操作远程mysql数据库实现单表增删改查操作

package MysqlTest; import java.sql.DriverManager; import java.sql.ResultSet; import com.mysql.jdbc.Connection; import com.mysql.jdbc.PreparedStatement; import com.mysql.jdbc.Statement; public class MysqlTest02 { public static void main(String[] args)

MySQL数据库2表的增删改查

[TOC] 一.数据表(文件): 1.1增 1.1.1列表的创建: create table 表名(字段名 列约束 [可选的参数] , ### 记住加逗号 字段名 列约束 [可选的参数] , ### 记住加逗号 字段名 列约束 [可选的参数] ### 最后一行不加逗号 )charset=utf-8; ### 后面加分号 例子: create table t1( id int, name char(5) )charset=utf-8; 1.1.2增加数据: insert into 表明 (列1,,

mysql操作数据库进行封装实现增删改查功能

SqlTool.class.php <?php class SqlTool{ private $conn; private $host = "localhost"; private $user = "root"; private $password = "root"; private $db = "test1"; /* 连接数据库的构造方法 */ function SqlTool(){ $this->conn =