python - pymysql模块
pymsql 模块
基本应用介绍:
# 安装模块 pip install PyMySql # 导入模块 import pymysql # 配置连接信息 config = { 'host':'127.0.0.1', 'port':3306, 'user':'root', 'password':'12345678', 'db':'anec', 'charset':'utf8' } # 连接数据库 db = pymysql.connect(**config) # 获取游标 start = db.cursor() #默认获取数据的格式为元组格式 cursor = db.cursor(cursor=pymysql.cursors.DictCursor) #设置cursor设置为pymysql.cursors.DictCursor,可以将显示数据为 字典格式 cursor.scroll(1,mode='relative') # 相对当前位置移动 cursor.scroll(2,mode='absolute') # 相对绝对位置移动 # 第一个值为移动的行数,整数为向下移动,负数为向上移动,mode指定了是相对当前位置移动,还是相对于首行移动 # 执行sql语句 start.execute() # 执行单条语句 start.executemany() # 执行多条语句 #获取单条数据 dp = start.fetchone() # 获取所有数据 dp = start.fetchall() # 获取指定条数数据 dp = start.fetchone(3) #获取3条数据 # 关闭数据库连接 db.close() # ------------------------------------------------- # 使用预处理语句创建表 sql = """CREATE TABLE test1 ( FIRST_NAME CHAR(20) NOT NULL, LAST_NAME CHAR(20), AGE INT, SEX CHAR(1), INCOME FLOAT )""" start.execute(sql) # ------------------------------------------------- # SQL 查询语句 sql = "SELECT * FROM EMPLOYEE WHERE INCOME > '%d'" % 1000 try: # 执行SQL语句 start.execute(sql) # 获取所有记录列表 results = start.fetchall() for row in results: print (row) except: print ("Error: unable to fetch data") # ------------------------------------------------- # SQL 插入语句 sql = """INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES ('Mac', 'Mohan', 20, 'M', 2000)""" # 可以 sql2 = "INSERT INTO EMPLOYEE(FIRST_NAME, \ LAST_NAME, AGE, SEX, INCOME) \ VALUES ('%s','%s','%d','%c','%d')" % \ ('Mac', 'Mohan', 20, 'M', 2000) try: # 执行sql语句 start.execute(sql) # 提交到数据库执行 db.commit() except: # 如果发生错误则回滚 db.rollback() # ------------------------------------------------- # SQL 更新语句 sql = "UPDATE EMPLOYEE SET AGE = AGE + 1 WHERE SEX = '%c'" % ('M') try: # 执行SQL语句 start.execute(sql) # 提交到数据库执行 db.commit() except: # 发生错误时回滚 db.rollback() # ------------------------------------------------- # 使用 execute() 方法执行 SQL,如果表存在则删除 start.execute("DROP TABLE IF EXISTS EMPLOYEE") # SQL 删除语句 sql = "DELETE FROM EMPLOYEE WHERE AGE > '%d'" % (20) try: # 执行SQL语句 start.execute(sql) # 提交修改 db.commit() except: # 发生错误时回滚 db.rollback()
上下文管理协议(示例)
# pymsql 支持 上下文管理协议 import pymysql config={ "host":"127.0.0.1", "user":"root", "password":"12345678", "database":"test"} db = pymysql.connect(**config) with db.cursor(cursor=pymysql.cursors.DictCursor) as cursor: #获取数据库连接的对象 sql = "SELECT * FROM userinfo" cursor.execute(sql) res = cursor.fetchone() print(res) cursor.scroll(2,mode='relative') res = cursor.fetchone() print(res) cursor.close() db.close()
简易封装pymysql类模块(数据表操作,查询/添加/修改/删除)
import pymysql class Mysql: def __init__(self,db_dict): self.db = pymysql.connect(**db_dict) self.cursor = self.db.cursor(cursor=pymysql.cursors.DictCursor) def __del__(self): self.cursor.close() self.db.close() def query(self,info): self.cursor.execute(info) datainfo = self.cursor.fetchall() return datainfo def insert(self,tn,dict_data): ''' :param tn: tablename 表名 :param dict_data: key值为字段,value为数据值 :return: 执行成功返回OK ''' try: key = ','.join([k for k in dict_data]) val = tuple([v for v in dict_data.values()]) sql = """insert into %s(%s)values%s; """ % (tn,key,val) self.cursor.execute(sql) self.db.commit() return 'OK' except: self.db.rollback() def insert_many(self,tn,list_dict_data): ''' :param tn: tablename 表名 :param list_dict_data: 输入 list[dict{}] 数据类型,dict{key值为字段,value为数据值} :return: 执行成功返回OK ''' try: for dict_data in list_dict_data: key = ','.join([k for k in dict_data]) val = tuple([v for v in dict_data.values()]) sql = """insert into %s(%s)values%s; """ % (tn,key,val) self.cursor.execute(sql) self.db.commit() return 'OK' except: self.db.rollback() def update(self,tn,key,val,tj,**kwargs): try: sql = r"""update %s set %s = '%s' where %s ;"""%(tn,key,val,tj) self.cursor.execute(sql) self.db.commit() return 'OK' except: self.db.rollback() def dele(self,tn,tj,**kwargs): try: sql = r"""delete from %s where %s""" % (tn,tj) self.cursor.execute(sql) self.db.commit() return 'OK' except: self.db.rollback() def dele_table(self,tn,mode=1): """ :param tn: 表名 :param mode: 模式1,只删除数据不删表 模式2,删除整个表 :return: 返回OK 表示操作成功 """ try: if mode == 1: sql ="""truncate %s;"""% tn self.cursor.execute(sql) self.db.commit() return 'OK' elif mode == 2: sql = """drop table %s;""" % tn self.cursor.execute(sql) self.db.commit() return 'OK' except: self.db.rollback() config = { 'host':'localhost', 'port':3306, 'user':'root', 'password':'12345678', 'db':'anec2', 'charset':'utf8' } test1 = Mysql(config) # # # #查询数据 # dp = test1.query("select * from t1") # for i in dp: # print(i) # #插入单条 字典数据 # dict_data = {'name':'小华','phone':998123,"email":"232323232@qq.com"} # dp = test1.insert('t2',dict_data) # print(dp) # # #插入多条列表[字典]数据 : [{'name':'alex3'},] # list_dict_data = [{'name':'小妹','phone':932323,"email":"2335433232@qq.com"}, # {'name': '小佛', 'phone': 99421323, "email": "433232@qq.com"}, # {'name': '小带', 'phone': 9932323, "email": "33445323232@qq.com"}] # dis = test1.insert_many('t2',list_dict_data) # print(dis) # # 修改数据信息 # #方式一: # test1.update('t1', 'name', 'abcabc','id=64') # # #方式二: # x = { # 'tn':'t1', # 'key':'name', # 'val':"123", # 'tj':'id=63'} # test1.update(**x) # # # 删除数据 # #方式一: # dp = test1.dele("t1","id >73") # print(dp) # #方式二: # x = { # 'tn':'t1', # 'tj':'id=73'} # dp = test1.dele(**x) # print(dp) # # 删除表 # #mode = 1 ,只删除数据,不删表(默认值) # #mode = 2 ,删除整个表 # dp= test1.dele_table('t1',mode=1) # print(dp)
既要脚踏实地,也需仰望天空