这篇文章主要介绍了python中操作mysql的方法,具有一定借鉴价值,需要的朋友可以参考下。希望大家阅读完这篇文章后大有收获。下面让小编带着大家一起了解一下。

mysql 使用
启动服务
sudo systemctl start mysql
pip3 install pymysql
python 操作数据库:
import pymysql
class MyDb():
def __init__(self, host, user, passwd, db):
self.__db = pymysql.connect(host, user, passwd, db)
self.__cursor = self.__db.cursor()
# 增删改-数据库
def set(self, sql):
try:
self.__cursor.execute(sql)
self.__db.commit()
except Exception as e:
self.__db.rollback()
print('Execute Error: \n {e}')
# 查-数据库
def get(self, sql, fetchone=True):
self.__cursor.execute(sql)
try:
if fetchone == True:
data = self.__cursor.fetchone()
else:
data = self.__cursor.fetchall()
except Exception as e:
print('Execute Error: \n {e}')
data = None
finally:
return data
# 关闭数据库
def close(self):
self.__db.close()