一、实例
import os
import sys
import pymysql
'''
该类主要功能是链接数据库然后执行查询,反馈想要的结果
'''
curPath = os.path.abspath(os.path.dirname(__file__))
rootPath = os.path.split(curPath)[0]
sys.path.append(rootPath)
class Mysql():
# 初始化数据库
def __init__(self, host, port, db, user, password, charset='utf8'):
self.db = pymysql.connect(host=host, port=port, db=db, user=user, password=password,) #打开数据库连接
self.cursor = self.db.cursor() # 使用cursor()方法创建一个游标对象cursor
# 执行查询
def sql_result(self, sql):
try:
self.cursor.execute(sql) #使用execute()方法执行SQL查询
data = self.cursor.fetchall() #使用fetchall()方法获取所有数据
return list(data)
except:
raise ValueError('查询出错')
finally:
self.cursor.close() # 关闭游标
self.db.close() # 关闭数据库
# 更新语句
def update(self, sql):
try:
self.cursor.execute(sql) # 使用execute()方法执行SQL查询
self.db.commit() #提交到数据库执行
except:
self.db.rollback() #发生错误时回滚
finally:
self.cursor.close() #关闭游标
self.db.close() # 关闭数据库
# 删除语句
def delete(self, sql):
try:
self.cursor.execute(sql) # 使用execute()方法执行SQL查询
self.db.commit() # 提交到数据库执行
except:
self.db.rollback() # 发生错误时回滚
finally:
self.cursor.close() # 关闭游标
self.db.close() #关闭数据库
# 查询结果转换
def reslut_replace(self, sql):
result = self.sql_result(sql)
if result == []:
result = ''
else:
result = result[0][0]
return str(result)
# 执行其他操作
def user_database(self, sql):
self.cursor.execute(sql)
if __name__ == "__main__":
db = Mysql(user='mysql', db='testdevplatform', password='哈哈哈哈哈哈', host='localhost', port=3306, charset='utf8')
sql = "select * from world.city "
data = db.sql_result(sql)
print(data)
1、data = cursor.fetchone() #使用fetchane()方法获取单条数据
data = self.cursor.fetchall() #使用fetchall()方法获取所有数据
2、== cursor.execute(sql) # 执行sql语句==
== db.commit() #提交到数据库执行==
db.rollback() #如果发生错误则回滚
3、commit()方法游标的所有更新操作,rollback()方法回滚当前游标的所有操作。