发布时间:2019-08-26 07:17:47编辑:auto阅读(2213)
环境:python 3.6.1 + mysql 5.1
Python3 支持用 pymysql 模块来链接数据库
#导入pymysql模块
import pymysql
class MYSQL:
# 初始化函数,初始化连接列表
def __init__(self,host,user,pwd,dbname):
self.host = host
self.user = user
self.pwd = pwd
self.dbname = dbname
# 获取数据库游标对象cursor
# 游标对象:用于执行查询和获取结果
def getCursor(self):
# 建立数据库连接
self.db = pymysql.connect(self.host,self.user,self.pwd,self.dbname)
# 创建游标对象
cur = self.db.cursor()
# 返回
return cur
# 查询操作
def queryOperation(self,sql):
# 建立连接获取游标对象
cur = self.getCursor()
# 执行SQL语句
cur.execute(sql)
# 获取数据的行数
row = cur.rowcount
# 获取查询数据
# fetch*
# all 所有数据,one 取结果的一行,many(size),去size行
dataList = cur.fetchall()
# 关闭游标对象
cur.close()
# 关闭连接
self.db.close()
# 返回查询的数据
return dataList,row
# 删除操作
def deleteOperation(self,sql):
# 获取游标对象
cur = self.getCursor()
try:
# 执行SQL语句
cur.execute(sql)
# 正常结束事务
self.db.commit()
except Exception as e:
print(e)
# 数据库回滚
self.db.rollback()
# 关闭游标对象
cur.close()
# 关闭数据库连接
self.db.close()
# 数据更新
def updateOperation(self,sql):
cur = self.getCursor()
try:
cur.execute(sql)
self.db.commit()
except Exception as e:
print(e)
self.db.rollback()
cur.close()
self.db.close()
# 添加数据
def insertOperation(self,sql):
cur = self.getCursor()
try:
cur.execute(sql)
self.db.commit()
except Exception as e:
print(e)
self.db.rollback()
cur.close()
self.db.close()
上一篇: Python:操作PostgreSQL数
下一篇: 理解python中的闭包
48866
47933
38707
35858
30284
27039
26070
20903
20698
19066
501°
594°
604°
609°
586°
572°
637°
710°
828°
928°