Python访问MySQL数据库并实现其增删改查功能
概述:
对于访问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数据库并实现其增删改查功能的更多相关文章
- Python操作MySQL数据库完成简易的增删改查功能
说明:该篇博客是博主一字一码编写的,实属不易,请尊重原创,谢谢大家! 目录 一丶项目介绍 二丶效果展示 三丶数据准备 四丶代码实现 五丶完整代码 一丶项目介绍 1.叙述 博主闲暇之余花了10个小时写的 ...
- 关于利用PHP访问MySql数据库的逻辑操作以及增删改查实例操作
PHP访问MySql数据库 <?php //造连接对象$db = new MySQLi("localhost","root","",& ...
- 使用JDBC分别利用Statement和PreparedStatement来对MySQL数据库进行简单的增删改查以及SQL注入的原理
一.MySQL数据库的下载及安装 https://www.mysql.com/ 点击DOWNLOADS,拉到页面底部,找到MySQL Community(GPL)Downloads,点击 选择下图中的 ...
- MySQL数据库之表的增删改查
目录 MySQL数据库之表的增删改查 1 引言 2 创建表 3 删除表 4 修改表 5 查看表 6 复制表 MySQL数据库之表的增删改查 1 引言 1.MySQL数据库中,数据库database就是 ...
- 在python中连接mysql数据库,并进行增删改查
数据库在开发过程中是最常见的,基本上在服务端的编程过程中都会使用到,mysql是较常见的一种数据库,这里介绍python如果连接到数据库中,并对数据库进行增删改查. 安装mysql的python扩展 ...
- Mysql数据库和表的增删改查以及数据备份&恢复
数据库 查看所有数据库 show databases; 使用数据库 use 数据库名; 查看当前使用的数据库 select database(); 创建数据库 create database 数据库名 ...
- Java连接MySQL数据库,并进行增删改查
1.具体的代码实现 import java.sql.*; public class DatabaseService { /** * Create Connection * * @param dbtyp ...
- MySQL数据库 | 数据表的增删改查
MySQL数据的增删改查(crud) 本文结构 一.增加 create 二.修改 update 三.查询 retrieve(简单查询,下篇详细展开) 四.删除 delete 首先,创建简单的class ...
- python3.6 使用 pymysql 连接 Mysql 数据库及 简单的增删改查操作
1.通过 pip 安装 pymysql 进入 cmd 输入 pip install pymysql 回车等待安装完成: 安装完成后出现如图相关信息,表示安装成功. 2.测试连接 import ...
随机推荐
- uva10570 Meeting with Aliens
先证明把每次i放到i位置最后次数最少:感觉,可以,用归纳法? //在序列后再加一个相同的序列,就可以模拟用各个数字开头的情况了每个位置不对的只需要换一次54123 ,5固定->41235变成12 ...
- vue中状态管理vuex的使用分享
一.main.js中引入 store import store from './store' window.HMO_APP = new Vue({ router, store, render: h = ...
- ibatis 实现 物理级别的 分页 兼容多种数据库(转载)
最近在看iBatis时,想做用动态Sql做个分布.因为在做项目时用iBator工具生成没有分页的功能,只有一些我们常用的功能.所以要对生成后的代码做修改.我在Java高手真经的一书中看到有做了MySq ...
- UVa-133-救济金发放
这题的话,我们首先对于移动函数可以知道,因为只是顺逆的关系,也就是加一或者减一,所以我们每次移动的时候,都补上一个小于n的最大整数,然后取模,这样就不会有负数,而且加之后的结果不会超过2*n,所以我们 ...
- python中的参数、全局变量及局部变量
1.位置参数.关键字参数.默认参数的使用 位置参数.关键字参数 def test(x,y,z): print(x) print(y) print(z) test(1,2,3) #位置参数,必须一一对应 ...
- Ubuntu 和 centos7 服务的启动
Ubuntu 下: /etc/init.d/nginx start | stop | reload Centos7下: service nginx start | stop | reload
- redis搭建配置
1 .去官方下载 2.解压tar 3.进入解压目录 编译 4.将编译好的目录移动到制定位置.做软连接 .配置环境便利 5.创建数据保存目录.创建配置文件 [root@radis ~]# vim /da ...
- Python机器学习及实践+从零开始通往Kaggle竞赛之路
内容简介 本书面向所有对机器学习与数据挖掘的实践及竞赛感兴趣的读者,从零开始,以Python编程语言为基础,在不涉及大量数学模型与复杂编程知识的前提下,逐步带领读者熟悉并且掌握当下最流行的机器学习.数 ...
- MySQL账户管理和主从同步
账户管理 在生产环境下操作数据库时,绝对不可以使用root账户连接,而是创建特定的账户,授予这个账户特定 的操作权限,然后连接进行操作,主要的操作就是数据的CRUD(增删改查) MySQL账户体系:根 ...
- LeetCode(80)Remove Duplicates from Sorted Array II
题目 Follow up for "Remove Duplicates": What if duplicates are allowed at most twice? For ex ...