import pymysql
# mysql class
class MySqlUtil(object):
# 连接数据库,初始化游标
def __init__(self):
self.conn = pymysql.connect(host=db_host,
user=db_user,
password=db_pwd,
db=db)
self.cursor = self.conn.cursor()
# 从数据库中获取数据
def get_data_from_db(self, sql):
try:
self.cursor.execute(sql)
results = self.cursor.fetchall()
return results
except pymysql.Error as e:
print('Mysql get_data_from_db Error {0}:'.format(e))
# 数据库执行插入、删除、创建表、删除表、、、
def exec_db(self, sql):
try:
cur = self.conn.cursor()
cur.execute(sql)
self.conn.commit()
except pymysql.Error as e:
print('Mysql exec_db Error {}'.format(e))
# 析构函数实现数据库关闭
def __del__(self):
self.cursor.close()
python 连接mysql封装
最新推荐文章于 2025-04-14 22:26:17 发布