示例:cur.fetch…函数
#此示例演示 cur.fetchone cur.fetchmany方法的使用 import pymysql try: db = pymysql.connect(host = 'localhost',user='root',\ password = '7952852741',database = 'db1',charset='utf8') cur = db.cursor() sql_select = "select * from sheng;" cur.execute(sql_select) data1 = cur.fetchone() print(data1) data2 = cur.fetchmany(3) print(data2) #for m in data2: # print(m) 可以遍历每个大元组里的小元组 data3 = cur.fetchall() print(data3) cb.commit() except Exception as e: print(e); cur.close() db.close() 参数化操作(防止sql注入攻击) cur.execute(sql语句,[参数列表]) import db = pymysql.connect(host = 'localhost',user='root',\ password = '7952852741',database = 'db1',charset='utf8') cur = db.cursor() s_id = input("请输入省编号") s_name = input("请输入省名称") try: sql_insert = "insert into sheng values(%s,%s);" cur.execute(sql_insert,[s_id,name]) print("succeed") db.commit() except Exception as e: db.rollback() #错误即事务回滚 print("failed",e) cur.close() db.close() python与mysql交互重复代码的封装 #此代码用来封装mysql的重用代码 from pymysql import * class mysqlpython: def __init__(self,database, host='localhost', user = "root", password=123456789', port = 3306, charset='utf8'): '''传入默认参数''' self.user = user self.host = host self.password = password self.port = port self.charset = charset self.database = database def open(self): '''连接数据库并打开游标''' self.db = connect(host = self.host, user = self.user, port = self.port, password=self.password, database = self.database, charset = self.charset) self.cur = self.db.cursor() def sql_do(self,sql,L=[]): '''执行sql语句''' try: if L == []: self.cur.execute(sql) else: self.cur.execute(sql,L) self.db.commit() except Exception as e: print('failed',e) self.close() def all(self,sql,L=[]): '''查看表信息''' try: self.open() self.cur.execute(sql,L) result = self.cur.fetchall() self.db.commit() return result except Exception as e: self.db.rollback() print('Failed',e) self.close() def close(self): '''关闭数据库连接''' self.cur.close() self.db.close() 业务方面:交互数据的加密 #采用sha1算法对用户账号密码的加密 from hashlib import sha1 from mysqlpython import * uname = print("请输入用户账号:") pwd = print("请输入用户密码:") s1 = sha1() #建立sha1对象 s1.update(pwd.encode("utf8")) #对pwd进行sha1加密 pwd2 = s1.hexdigest() #对加密后的结果转换为16进制 sql_select = "select password from user where uname = %s;" db1 = mysqlpython("db1") result = db1.all(sql_select,[uname]) #返回数据的大元组 if len(result) == 0: print("账号不存在!") elif result[0][0] != pwd2: print("密码错误!") else: print("登录成功!")