当前位置:Gxlcms > 数据库问题 > pymysql模块的使用

pymysql模块的使用

时间:2021-07-01 10:21:17 帮助过:2人阅读

实现:使用Python实现用户登录,如果用户存在则登录成功(假设该用户已在数据库中) import pymysql user = input(请输入用户名:) pwd = input(请输入密码:) # 1.连接 conn = pymysql.connect(host=127.0.0.1, port=3306, user=root, password=‘‘, db=db8, charset=utf8) # 2.创建游标 cursor = conn.cursor() #注意%s需要加引号 sql = "select * from userinfo where username=‘%s‘ and pwd=‘%s‘" %(user, pwd) print(sql) # 3.执行sql语句 cursor.execute(sql) result=cursor.execute(sql) #执行sql语句,返回sql查询成功的记录数目 print(result) # 关闭连接,游标和连接都要关闭 cursor.close() conn.close() if result: print(登陆成功) else: print(登录失败)

 

二、execute()之sql注入

最后那一个空格 , 在一条sql 语句中如果遇到  select * from userinfo where username = mjj -- asdsadn and pwd = ‘‘ 则-- 之后的条件被注释掉了(注意-- 后面还有一个空格)

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

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

 

技术分享图片

 

 

 

 

技术分享图片

 

 

 

 

 

 

解决方法:

# 原来是我们对sql进行字符串拼接
# sql="select * from userinfo where name=‘%s‘ and password=‘%s‘" %(username,pwd)
# print(sql)
# result=cursor.execute(sql)

#改写为(execute帮我们做字符串拼接,我们无需且一定不能再为%s加引号了)
sql="select * from userinfo where name=%s and password=%s" #!!!注意%s需要去掉引号,因为pymysql会自动为我们加上
result=cursor.execute(sql,[user,pwd]) #pymysql模块自动帮我们解决sql注入的问题,只要我们按照pymysql的规矩来。

 

pymysql模块的使用

标签:python   实现   程序   创建   print   word   res   password   mys   

人气教程排行