python pymysql_python的pymysql模块简介

一.介绍

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

pip3 install pymysql

二.操作简介

importpymysql#链接

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()ifres:print('登录执行成功')else:print('失败')

三.execute()之sql注入

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

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

#1、sql注入之:用户存在,绕过密码

egon' -- 任意字符

#2、sql注入之:用户不存在,绕过用户与密码

xxx' or 1=1 -- 任意字符

932413-20180711225725735-1030426359.png

932413-20180711225732551-354341037.png

932413-20180711225740595-903368903.png

解决方法:#原来是我们对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的增删改语句写入

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)

conn.commit()

如果数据库引擎是innodb那么增删改后需要用conn.commit()来确认修改不然不起效

sql = 'INSERT INTO student VALUES(9, "wang1", "male", 6)'sql1= 'select * from student'res=cursor.execute(sql)

cursor.execute(sql1)print(cursor.fetchall())#不加conn.commit()的结果

((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), (9, 'wang1', 'male', 6))

虽然会话有显示但是实际库中没有

932413-20180712154937998-1626078588.png

重新执行加入commit()生效

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

conn.commit() # 确认插入操作

932413-20180712155217798-1235005411.png

五.查询

表内容如下:

932413-20180711180904764-461958162.png

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值