import pymysql
from Conf.Read_ini import ConfigFile
class SQLs(ConfigFile):
def __init__(self):
ConfigFile.__init__(self)
self.db = pymysql.connect(host=self.database_host,
user=self.database_user,
password=self.database_password,
db=self.database_db,
port=int(self.database_port),
charset='utf8'
)
# 查询操作
def select_data(self, sql):
# 使用 cursor() 方法创建一个游标对象 cursor
cur = self.db.cursor()
# 使用 execute() 方法执行 SQL查询
cur.execute(sql)
# 使用 fetch all 方法获取所有数据.
sql_result = cur.fetchall()
# 返回所有数据
return sql_result
# 关闭数据库连接
self.db.close()
# 插入操作
def insert_data(self, sql):
# 使用cursor()方法获取操作游标
cur = self.db.cursor()
sql_insert = sql
try:
cur.execute(sql_insert)
# 提交
self.db.commit()
except Exception as e:
print(e)
# 错误回滚
self.db.rollback()
finally:
self.db.close()
# 更新操作
def update_data(self, sql):
# 使用cursor()方法获取操作游标
cur = self.db.cursor()
sql_update = sql
try:
cur.execute(sql_update)
# 提交
self.db.commit()
except Exception as e:
print(e)
# 错误回滚
self.db.rollback()
finally:
self.db.close()
# 删除操作
def delete_data(self, sql):
# 使用cursor()方法获取操作游标
cur = self.db.cursor()
sql_delete = sql
try:
cur.execute(sql_delete)
# 提交
self.db.commit()
except Exception as e:
print(e)
# 错误回滚
self.db.rollback()
finally:
self.db.close()