python的pymysql模块简介

一.介绍

在python中用pymysql模块来对mysql进行操作,该模块本质就是一个套接字客户端软件,使用前需要事先安装

pip3 install pymysql

二.操作简介

import pymysql

#链接
conn=pymysql.connect(host='localhost',user='root',password='123',database='test',charset='utf8')
#游标
cursor=conn.cursor() #执行完毕返回的结果集默认以元组显示
#执行sql语句
sql='select * from userinfo where name="%s" and password="%s"' %(user,pwd) #注意%s需要加引号
print(sql)
res=cursor.execute(sql) #执行sql语句,返回sql查询成功的记录数目
print(res)

cursor.close()
conn.close()

if res:
    print('登录执行成功')
else:
    print('失败')

三.execute()之sql注入

符号--会注释掉它之后的sql,正确的语法:--后至少有一个任意字符

注入的原理就是通过拼接和注释绕过验证

#1、sql注入之:用户存在,绕过密码
egon' -- 任意字符

#2、sql注入之:用户不存在,绕过用户与密码
xxx' or 1=1 -- 任意字符

解决方法:
# 原来是我们对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 student VALUES(9, "wang1", "male", 6)'
# sql = 'update student set class_id = 4 where sname = "wang1"'
# sql = 'delete from student where sname = "wang1"'
res = cursor.execute(sql)
print(res)

五.查询

fetchone,fetchmany,fetchall

sql = 'select * from student'
res = cursor.execute(sql)
print(cursor.fetchone()) #查询一条记录
print(cursor.fetchone())
print(cursor.fetchmany(2)) #查询两条记录
print(cursor.fetchall()) #查询剩余所有记录
print(res) #显示几条记录

执行结果以元组形式显示
(1, '乔丹', 'female', 1)
(2, '艾佛森', 'female', 1)
((3, '科比', 'male', 2), (4, '小明', 'male', 3))
((5, '小芳', 'female', 8), (6, '小明', 'female', 9), (7, 'alex', 'male', 6), (8, 'wang', 'male', 5))
8

lastrowid 

获取插入的最后一条数据的自增ID,只能显示数据表属性是自增字段的值

sql = 'INSERT INTO student VALUES(9, "wang1", "male", 6)'
res = cursor.execute(sql)
print(cursor.lastrowid)

执行结果
9

猜你喜欢

转载自www.cnblogs.com/fanhk/p/9296049.html