在开发中经常要用到mysql数据库的增删改查操作,每次都在重新连接、重新执行、重新关闭吗?代码不是一次性使用的,接下来将告诉你,有些代码是只用写一遍,以后直接拿过来用的。
pymysql、configparser安装
# pymysql安装
pip install pymysql -i http://pypi.douban.com/simple
configparser用来读取配置文件
# configparser安装
pip install configparser -i http://pypi.douban.com/simple
database.ini文件
将数据库连接的信息写到固定的配置文件中去,方便以后的管理和使用。
新建database.ini文件,编写配置信息(注意变量后面不用加引号如:”localhost”)
# 配置文件
[mysql]
host = localhost
port = 3306
user = root
password = 123456
database = test
[pgsql]
host = 127.0.0.1
port = 3306
user = root
password = 123456
database = test
构建数据库连接
确保安装好了pymysql和configparser两个包。
import os
import pymysql
import configparser
class Mysql():
def __init__(self, reset_config=None, section='mysql',
file='database.ini'):
"""
mysql 构造mysql数据化连接
Args:
reset_config ([dict], optional): [重置后传入的数据库配置信息]
section ([str], optional): [配置文件中的段, 默认为mysql]
file ([str], optional): [默认database.ini为配置文件]
"""
self.PORJECT_DIR = os.path.dirname(os.path.abspath(__file__)) # 测试项目路径
self.fileName = self.PORJECT_DIR + '/' + file # 配置文件路径
if reset_config:
self.db = pymysql.connect(**reset_config)
else:
self.config = configparser.ConfigParser() # 拿到一个配置对象
if not os.path.exists(self.fileName):
raise FileExistsError("数据库配置文件不存在")
self.config.read(self.fileName, encoding='utf-8') # 读取配置文件,注意编码
if not self.config.has_section(section):
raise ValueError("配置文件中mysql不存在")
mysql_config = self.config.items(section) # 读取[mysql]配置信息 list
mysql_config = dict(map(lambda x: [x[0], x[1]], mysql_config))
mysql_config.update({"port": int(mysql_config.get("port"))}) # 默认读取端口为字符串‘3306’,需转换成int
self.db = pymysql.connect(**mysql_config)
self.cursor = self.db.cursor(pymysql.cursors.DictCursor) # 创建游标
def __del__(self):
# 自动销毁数据库连接
self.db.close()
def create(self, table, data):
"""
创建表
table: str 表名
data: list 创建表字段
"""
self.cursor.execute("DROP TABLE IF EXISTS {}".format(table))
sql = ' VARCHAR(255),'.join(data)
sql_query = "CREATE TABLE %s ( %s VARCHAR(255))" % (table, sql)
try:
self.cursor.execute(sql_query)
except Exception as e:
print(e.args)
def select(self, sql) -> list:
"""[查询数据]
Args:
sql ([str]): [需要查询的sql语句]
"""
self.cursor.execute(sql)
data = self.cursor.fetchall()
return data
def select_one(self, sql) -> dict:
"""[查询数据]
Args:
sql ([str]): [需要查询的sql语句]
"""
self.cursor.execute(sql)
data = self.cursor.fetchone()
return data
def insert(self, table, data, *args):
"""[数据保存到指定表中]
Args:
table ([str]): [表名]
data ([dict]): [数据字典]
"""
if data and isinstance(data, dict):
keys = ', '.join(data.keys())
values = ', '.join(['%s'] * len(data))
sql_query = 'insert into %s (%s) values (%s)' % (table, keys, values)
try:
# print(sql_query % tuple(data.values()))
self.cursor.execute(sql_query, tuple(data.values()))
return True
except Exception as e:
print(e.args)
self.db.rollback()
def update_insert(self,table, data, *args):
"""[先更新数据,如果数据不存在时进行insert]
Args:
table ([str]): [表名]
data ([dict]): [数据字典]
"""
keys = ', '.join(data.keys())
values = ', '.join(['%s'] * len(data))
a = tuple(data.keys())
b = tuple(data.values())
sql = dict(map(lambda x,y: [x, y], a, b))
updatefiled = ','.join([str(k) + '=' + str(v) for k, v in sql.items()])
sql_query = 'insert into %s (%s) values (%s) ON DUPLICATE KEY UPDATE %s' % (table, keys, values, updatefiled)
try:
# print(sql_query % tuple(data.values()))
self.cursor.execute(sql_query, tuple(data.values()))
return True
except Exception as e:
print(e.args)
self.db.rollback()
def update_or_delete(self, sql):
"""[更新/删除数据]
Args:
sql ([str]): [sql更新数据]
"""
self.cursor.execute(sql)
self.db.commit()
def commit(self):
"""[sql执行]
"""
self.db.commit()
def close(self):
# 关闭连接
self.db.close()
默认是读取database.ini文件的[mysql]下的配置信息,可以重置mysql连接的配置信息:
reset_conf = {
'host': 'localhost',
'user': 'root',
'password': '123456',
'port': 3306,
'database': 'test',
}
使用os动态的获取当前文件夹将配置文件的路径拼接起来。
self.PORJECT_DIR = os.path.dirname(os.path.abspath(__file__)) # 测试项目路径
self.fileName = self.PORJECT_DIR + '/' + file # 配置文件路径
当配置文件不存在时,会抛出异常。
if not os.path.exists(self.fileName):
raise FileExistsError("数据库配置文件不存在")
当配置文件中没有写[mysql]时也会抛出异常。
if not self.config.has_section(database):
raise ValueError("配置文件中mysql不存在")
由于使用configparser读取database.ini信息时,将得到的数字类型转成了字符串类型,这里需要转换成数字类型。
mysql_config.update({"port": int(mysql_config.get("port"))}) # 默认读取端口为字符串‘3306’,需转换成int
关闭连接
def __del__(self):
# 自动销毁数据库连接
self.db.close()
def close(self):
# 关闭连接
self.db.close()
__del__(),对象销毁时,会自动执行。
close方法,主动调用关闭函数。
使用
创建数据表
if __name__ == "__main__":
# 实例化对象
mysql = Mysql()
# 创建数据表
mysql.create('test01', ['name', 'age', 'height'])
mysql.commit()
mysql.close()
新增数据
datas = [{"name": "9527", 'age': 18, 'height': 180},{"name": "1024", 'age': 20, 'height': 170}]
for data in datas:
res = mysql.insert('test01', data)
mysql.commit()
删除or修改
# 删除或者修改
sql = "delete from aaa where name='aaa'"
mysql.update_or_delete('test01', data)
mysql.commit()
增加时更新
增加时更新(要设置唯一主键)。
# 增加时更新
datas = [{"name": "9527", 'age': 19, 'height': 180}, {"name": "1024", 'age': 55, 'height': 170}]
for data in datas:
res = mysql.update_insert('test01', data)
mysql.commit()
查询所有
sql = "select * from test01"
res = mysql.select(sql)
print(res)
>>[{'name': '1024', 'age': '8', 'height': '170'}, {'name': '9527', 'age': '6', 'height': '180'}]
查询单条
sql = "select * from test01 where name='9527'"
res = mysql.select_one(sql)
print(res)
>> {'name': '9527', 'age': '6', 'height': '180'}
以上就是对pymysql的常用操作了,希望对大家有所帮助。
感兴趣的可以关注作者微信公众号:程序员9527。