import pymysql
class DBUtil:
__conn = None
__cursor = None
@classmethod
def __get_conn(cls): # 获取连接
if cls.__conn == None:
cls.__conn = pymysql.connect(host="localhost",
port=3306,
user="root",
password="123456",
database="books")
return cls.__conn
@classmethod
def __get_cursor(cls): # 获取游标
if cls.__cursor == None:
cls.__cursor = cls.__get_conn().cursor()
return cls.__cursor
@classmethod
def __close_cursor(cls): # 关闭游标
if cls.__cursor != None:
cls.__cursor.close()
cls.__cursor = None
@classmethod
def __close_conn(cls): # 关闭连接
if cls.__conn != None:
cls.__conn.close()
cls.__conn = None
@classmethod
def mysql(cls, sql_str): # 程序入口
try:
cursor = cls.__get_cursor()
cursor.execute(sql_str)
str = sql_str.split(" ")[0]
if str == "select":
return cursor.fetchall()
else:
cls.__conn.commit()
return cursor.rowcount
except Exception as e:
cls.__conn.rollback()
print(e)
finally:
cls.__close_cursor()
cls.__close_conn()
封装Python连接MySQL数据库为工具类
最新推荐文章于 2024-06-20 10:06:13 发布