import pymysql
class Mysql_Python:
def __init__(self,host,port,user,password,database):
self.host = host
self.port = port
self.user = user
self.password = password
self.database = database
def coonect(self):
db = pymysql.connect(host=self.host,port=self.port,user=self.user,password=self.password,database=self.database)
cursor = db.cursor()
return db,cursor
def select(self,cursor,sql_str):
try:
cursor.execute(sql_str) # 执行SQL语句
results = cursor.fetchall() # 获取所有记录列表
return results
except:
print("Error: unable to fetch data")
print("失败")
def insert(self,db,cursor,sql_str):
try:
cursor.execute(sql_str) # 执行sql语句
db.commit() # 提交到数据库执行
print("成功")
except:
db.rollback() # 如果发生错误则回滚
print("失败")
def delete(self,db,cursor,sql_str):
try:
cursor.execute(sql_str) # 执行SQL语句
db.commit() # 提交修改
print("成功")
except:
db.rollback() # 发生错误时回滚# 关闭连接
print("失败")
def updata(self,db,cursor,sql_str):
try:
cursor.execute(sql_str) # 执行SQL语句
db.commit() # 提交修改
print("成功")
except:
db.rollback() # 发生错误时回滚# 关闭连接
print("失败")
def close(self,db,cursor):
cursor.close()
db.close()