文章概要:
- 使用pymysql操作mysql数据库,
- 使用configparser库读取数据库配置文件,简单用法点我
import pymysql
import configparser
class Mysql:
def __init__(self):
config = self.getConf()
# **对字典变量解包
self.db = pymysql.connect(**config)
#读取配置
def getConf(self):
config = configparser.ConfigParser()
#读取database.conf配置文件
config.read('database.conf')
return dict(host=config.get('mysql', 'host'),
user=config.get('mysql', 'username'),
password=config.get('mysql', 'password'),
database=config.get('mysql', 'dbname'),
charset=config.get('mysql', 'charset')
)
#获取单条记录
def get_one(self, table='', where={}):
if not table:
print('表名不能为空!')
return
if not isinstance(where, dict):
print('where条件暂时只支持字典类型')
return
sql = "SELECT * FROM `{table}` ".format(table=table);
values = []
if where:
sql += ' WHERE'
for key, value in where.items():
sql += ' `{column}` = %s '.format(column=key)
values.append(value)
with self.db.cursor(pymysql.cursors.DictCursor) as cursor:
cursor.execute(sql, tuple(values))
return cursor.fetchone()
#获取多条记录
def get_all(self, table='', where={}):
if not table:
print('表名不能为空!')
return
if not isinstance(where, dict):
print('where条件暂时只支持字典类型')
return
sql = "SELECT * FROM `{table}` ".format(table=table);
values = []
if where:
sql += ' WHERE'
for key, value in where.items():
sql += ' `{column}` = %s '.format(column=key)
values.append(value)
with self.db.cursor(pymysql.cursors.DictCursor) as cursor:
cursor.execute(sql, tuple(values))
return cursor.fetchall()
#新增单条记录
def add_one(self,table='',data={}):
if not table:
print('表名不能为空!')
return
if not isinstance(data, dict):
print('数据只支持字典类型')
return
if not data:
print('需要添加的数据不能为空')
return
sql = 'INSERT INTO `{table}` ( '.format(table=table)
values = []
for key,value in data.items():
sql += '`{column}`,'.format(column=key)
values.append(value)
sql = sql.rstrip(',')
sql += ') VALUES ('
for i in range(0,len(values)):
sql += '%s,'
sql = sql.rstrip(',')
sql += ')'
try:
with self.db.cursor(pymysql.cursors.DictCursor) as cursor:
cursor.execute(sql,tuple(values))
print('数据插入成功!')
self.db.commit()
except:
print('数据插入失败!')
self.db.rollback()
#关闭连接
def __del__(self):
self.db.close()
if __name__ == '__main__':
print(Mysql().get_all('news'))
print(Mysql().add('news',{"title":"七大罪",'content':'《七大罪》是日本漫画家铃木央所著的少年漫画。2011年在讲谈社《周刊少年magazine》上以短篇的形式登场,获得好评后2012年于同本杂志上开始正式连载。'}))
几个注意点:
- pymysql操作数据库并不是直接使用连接句柄操作而是使用游标
- 关于pymysql.cursors.DictCursor是用来设置游标的返回类型,换句话说就是设置fetch获取数据时返回的类型
- 再使用游标进行写操作时注意使用try-except捕获异常并进行回滚,保证一组写操作执行都成功或者都失败
- 游标在获取的时候,默认会开启事务