Python3操作MySQL基于PyMySQL封装的类
Python3操作MySQL基于PyMySQL封装的类
在未使用操作数据库的框架开发项目的时候,我们需要自己处理数据库连接问题,今天在做一个Python的演示项目,写一个操作MySQL数据库的类,基于PyMySQL库在Python3上实现。在写业务逻辑代码的时候,可以方便很多,时间关系,没有写太完善,只写了常用的操作。
直接上代码:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'Python连接到 MySQL 数据库及相关操作(基于Python3)'
import pymysql.cursors
class Database:
""" Python连接到 MySQL 数据库及相关操作 """
"""
conf: 类参数,数据库的连接参数配置字典,含host、port、user、pw、db、charset(可选,默认utf8)
connected: 属性,True数据库连接成功,False连接失败
insert(self, table, val_obj): 方法,插入数据到数据表
table: 数据表名称
val_obj: 待插入数据的字段名和值的键值对字典
返回: 成功则返回新插入数据的主键ID,失败返回False
update(self, table, val_obj, range_str): 方法,更新数据表中的数据
table: 数据表名称
val_obj: 待更新数据的字段名和值的键值对字典
range_str: 更新范围的条件语句字符串
返回: 成功返回更新的行数,失败返回False
delete(self, table, range_str): 方法,在数据表中删除数据
table: 数据表名称
range_str: 删除范围的条件语句字符串
返回: 成功返回删除的行数,失败返回False
select_one(self, table, factor_str, field='*'): 方法,查询表中符合条件唯一的一条数据
table: 数据表名称
factor_str: 查询唯一条件语句字符串
field: 查询结果返回哪些字段,多个用逗号分隔,可选参数,默认返回所有字段
返回: 成功返回一条数据的字段名与值的一维字典,失败返回False
select_more(self, table, range_str, field='*'): 方法,查询表中符合条件的所有数据
table: 数据表名称
range_str: 查询条件语句字符串
field: 查询结果返回哪些字段,多个用逗号分隔,可选参数,默认返回所有字段
返回: 成功返回多条数据的字段名与值的二维字典,失败返回False
count(self, table, range_str='1'): 方法,统计数据表中符合条件的总函数
table: 数据表名称
range_str: 查询条件语句字符串,可选参数,默认表中所有行数
返回: 成功返回符合条件的行数,失败返回False
sum(self, table, field, range_str='1'): 方法,对数据表中某数值类型字段求和
table: 数据表名称
field: 需要求和的字段,可以是多个字段的计算公式
range_str: 需要求和的条件语句字符串,可选参数,默认表中所有行
返回: 成功返回求和结果,失败返回False
close(self): 方法,关闭数据库连接,对象销毁时也会自动关闭,所以多数时候不用特意调用
"""
connected = False
__conn = None
# 构造函数,初始化时直接连接数据库
def __init__(self, conf):
if type(conf) is not dict:
print('错误: 参数不是字典类型!')
else:
for key in ['host', 'port', 'user', 'pw', 'db']:
if key not in conf.keys():
print('错误: 参数字典缺少 %s' % key)
if 'charset' not in conf.keys():
conf['charset'] = 'utf8'
try:
self.__conn = pymysql.connect(
host=conf['host'],
port=conf['port'],
user=conf['user'],
passwd=conf['pw'],
db=conf['db'],
charset=conf['charset'],
cursorclass=pymysql.cursors.DictCursor)
self.connected = True
except pymysql.Error as e:
print('数据库连接失败:', end='')
# 插入数据到数据表
def insert(self, table, val_obj):
sql_top = 'INSERT INTO ' + table + ' ('
sql_tail = ') VALUES ('
try:
for key, val in val_obj.items():
sql_top += key + ','
sql_tail += val + ','
sql = sql_top[:-1] + sql_tail[:-1] + ')'
with self.__conn.cursor() as cursor:
cursor.execute(sql)
self.__conn.commit()
return self.__conn.insert_id()
except pymysql.Error as e:
self.__conn.rollback()
return False
# 更新数据到数据表
def update(self, table, val_obj, range_str):
sql = 'UPDATE ' + table + ' SET '
try:
for key, val in val_obj.items():
sql += key + '=' + val + ','
sql = sql[:-1] + ' WHERE ' + range_str
with self.__conn.cursor() as cursor:
cursor.execute(sql)
self.__conn.commit()
return cursor.rowcount
except pymysql.Error as e:
self.__conn.rollback()
return False
# 删除数据在数据表中
def delete(self, table, range_str):
sql = 'DELETE FROM ' + table + ' WHERE ' + range_str
try:
with self.__conn.cursor() as cursor:
cursor.execute(sql)
self.__conn.commit()
return cursor.rowcount
except pymysql.Error as e:
self.__conn.rollback()
return False
# 查询唯一数据在数据表中
def select_one(self, table, factor_str, field='*'):
sql = 'SELECT ' + field + ' FROM ' + table + ' WHERE ' + factor_str
try:
with self.__conn.cursor() as cursor:
cursor.execute(sql)
self.__conn.commit()
return cursor.fetchall()[0]
except pymysql.Error as e:
return False
# 查询多条数据在数据表中
def select_more(self, table, range_str, field='*'):
sql = 'SELECT ' + field + ' FROM ' + table + ' WHERE ' + range_str
try:
with self.__conn.cursor() as cursor:
cursor.execute(sql)
self.__conn.commit()
return cursor.fetchall()
except pymysql.Error as e:
return False
# 统计某表某条件下的总行数
def count(self, table, range_str='1'):
sql = 'SELECT count(*)res FROM ' + table + ' WHERE ' + range_str
try:
with self.__conn.cursor() as cursor:
cursor.execute(sql)
self.__conn.commit()
return cursor.fetchall()[0]['res']
except pymysql.Error as e:
return False
# 统计某字段(或字段计算公式)的合计值
def sum(self, table, field, range_str='1'):
sql = 'SELECT SUM(' + field + ') AS res FROM ' + table + ' WHERE ' + range_str
try:
with self.__conn.cursor() as cursor:
cursor.execute(sql)
self.__conn.commit()
return cursor.fetchall()[0]['res']
except pymysql.Error as e:
return False
# 销毁对象时关闭数据库连接
def __del__(self):
try:
self.__conn.close()
except pymysql.Error as e:
pass
# 关闭数据库连接
def close(self):
self.__del__()
Python3操作MySQL基于PyMySQL封装的类的更多相关文章
- Python中操作mysql的pymysql模块详解
Python中操作mysql的pymysql模块详解 前言 pymsql是Python中操作MySQL的模块,其使用方法和MySQLdb几乎相同.但目前pymysql支持python3.x而后者不支持 ...
- python3操作mysql教程
一.下载\安装\配置 1. python3 Python3下载网址:http://www.python.org/getit/ 当前最新版本是python3.2,下载地址是 http://www.pyt ...
- python3操作MySQL的模块pymysql
本文介绍Python3连接MySQL的第三方库--PyMySQL的基本使用. PyMySQL介绍 PyMySQL 是在 Python3.x 版本中用于连接 MySQL 服务器的一个库,Python2中 ...
- python操作mysql(pymysql + sqlalchemy)
pymysql pymsql是Python中操作MySQL的模块,其使用方法和MySQLdb几乎相同. 下载安装 pip3 install pymysql 使用操作 1.执行sql #!/usr/bi ...
- python3操作MySQL数据库
安装PyMySQL 下载地址:https://pypi.python.org/pypi/PyMySQL 1.把操作Mysql数据库封装成类,数据库和表先建好 import pymysql.cursor ...
- python操作mysql之pymysql
pymsql是Python中操作MySQL的模块,其使用方法和MySQLdb几乎相同.但目前pymysql支持python3.x而后者不支持3.x版本. 本文测试python版本:2.7.11.mys ...
- Python自动化运维之18、Python操作 MySQL、pymysql、SQLAchemy
一.MySQL 1.概述 什么是数据库 ? 答:数据的仓库,和Excel表中的行和列是差不多的,只是有各种约束和不同数据类型的表格 什么是 MySQL.Oracle.SQLite.Access.MS ...
- (转)Python中操作mysql的pymysql模块详解
原文:https://www.cnblogs.com/wt11/p/6141225.html https://shockerli.net/post/python3-pymysql/----Python ...
- Python操作MySQL:pymysql和SQLAlchemy
本篇对于Python操作MySQL主要使用两种方式: 原生模块 pymsql ORM框架 SQLAchemy pymsql pymsql是Python中操作MySQL的模块,其使用方法和MySQLdb ...
随机推荐
- Python超简单的爬取网站中图片
1.首先导入相关库 import requests import bs4 import threading #用于多线程爬虫,爬取速度快,可以完成多页爬取 import os 2.使用bs4获取htm ...
- git 使用详解(5)—— get log 查看提交历史
git log 查看 提交历史 在提交了若干更新之后,又或者克隆了某个项目,想回顾下提交历史,可以使用 git log 命令查看. 接下来的例子会用我专门用于演示的 simplegit 项目,运行下面 ...
- 数据挖掘算法(三)--logistic回归
数据挖掘算法学习笔记汇总 数据挖掘算法(一)–K近邻算法 (KNN) 数据挖掘算法(二)–决策树 数据挖掘算法(三)–logistic回归 在介绍logistic回归之前先复习几个基础知识点,有助于后 ...
- 使用.NET Core创建Windows服务 - 使用.NET Core工作器方式
原文:Creating Windows Services In .NET Core – Part 3 – The ".NET Core Worker" Way 作者:Dotnet ...
- 视频发布 2019 中国.NET 开发者峰会
2019 年,注定会是 .NET Core 社区发展的关键一年,诸多重大事件在这一年发生!正如大家所期待的那样,刷新中国 .NET 社区的年度盛会--2019 中国 .NET 开发者峰会(.NET C ...
- 在VS2017中连接到SQLite数据源(dbfist)
在VS2017中配置.连接到SQLite数据源(dbfist) 需要安装的VS插件 SQLite/SQL Server Compact ToolBox 这个插件安装后,在选择数据源时已经可以选择SQL ...
- screen虚拟终端工具
说明:有时候我们要执行一个命令或脚本,需要几小时甚至几天,但是不能中断,有时想查看当前输出信息的时候,可以将它丢到后台运行,但是后台运行却无法显示或输出相关信息出来:我们可以使用一个虚拟终端工具scr ...
- Vue项目中实现用户登录及token验证
学习博客:https://www.cnblogs.com/web-record/p/9876916.html
- C语言每日一练——第7题
一.题目要求 已知数据文件in.dat中存有200个四位数,把这些数存到数组a中,编写函数jsVal(),其功能是:把千位数字和十位数字重新组成一个新的含有两位数字的数ab(新数的十位数字是原四位数的 ...
- exports、module.exports 和 export、export default
先了解他们的使用范围. require: node 和 es6 都支持的引入export / import : 只有es6 支持的导出引入module.exports / exports: 只有 no ...