#安装pip3 install pymysql
链接、执行sql、关闭游标
import pymysql#链接conn=pymysql.connect( host='localhost', user='root', password='123', database='egon', charset='utf8')#游标# cursor=conn.cursor() #执行完毕返回的结果集默认以元组显示cursor=conn.cursor(cursor=pymysql.cursors.DictCursor) # 以字典的方式显示数据# pymysql操作数据库#执行sql语句user = input(">>>:").strip()pwd = input(">>>:").strip()sql='select * from userinfo where name="%s" and password="%s"' %(user,pwd) #注意%s需要加引号rows=cursor.execute(sql) #执行sql语句,返回sql查询成功的记录数目# 获取真实数据cursor.fetchone(),cursor.fetchall(),cursor.fetchmany(),类似管道取值,获取一条,所有,多条cursor.scroll(1,'relative') # 相对移动cursor.scroll(3,'absolute') # 绝对移动cursor.close()conn.close()
sql注入问题
# 不要手动去拼接查询的sql语句username = input(">>>:").strip()password = input(">>>:").strip()sql = "select * from user where username='%s' and password='%s'"%(username,password)# 用户名正确username >>>: abc' -- jjsakfjjdkjjkjs# 用户名密码都不对的情况username >>>: xxx' or 1=1 -- asdjkdklqwjdjkjasdljadpassword >>>: ''
解决方法:# 原来是我们对sql进行字符串拼接# sql="select * from userinfo where name='%s' and password='%s'" %(user,pwd)# print(sql)# res=cursor.execute(sql)#改写为(execute帮我们做字符串拼接,我们无需且一定不能再为%s加引号了)sql="select * from userinfo where name=%s and password=%s" #!!!注意%s需要去掉引号,因为pymysql会自动为我们加上res=cursor.execute(sql,(user,pwd)) #pymysql模块自动帮我们解决sql注入的问题,只要我们按照pymysql的规矩来
增删改
# 增sql = "insert into user(username,password) values(%s,%s)"rows = cursor.excute(sql,('jason','123'))# 修改sql = "update user set username='jasonDSB' where id=1"rows = cursor.excute(sql)"""增和改单单执行excute并不会真正影响到数据,需要再执行conn.commit()才可以完成真正的增改"""# 一次插入多行记录res = cursor,excutemany(sql,[(),(),()]conn.commit() #提交后才发现表中插入记录成功
查:fetchone,fetchmany,fetchall
import pymysqlconn = pymysql.connect( host="127.0.0.1", port=3306, user="root", password="", database="day41", charset="utf8")cursor = conn.cursor() # 获取游标,执行完毕的结果以元祖显示# cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)sql = "select * from userinfo"rows = cursor.execute(sql)res1 = cursor.fetchone()res2 = cursor.fetchone()res3 = cursor.fetchone()res4 = cursor.fetchmany(2)res5 = cursor.fetchall()print(res1)print(res2)print(res3)print(res4)print(res5)conn.commit()cursor.close()conn.close()