原生操作数据库模块 pymysql
pymsql是Python中操作MySQL的模块(其使用方法和MySQLdb几乎相同,在python3中,MySQLdb这个库已经不能继续使用了)
下载安装
pip3 install pymysql
another way:用集成开发环境pycharm安装模块:
File-->Settings-->Project:xxx-->Project Interpreter-->右侧有个小 ‘+’ 号,点击--->在输入框里输入要安装的模块(pymysql)-->左下角Install Package
如图:
使用步骤
连接数据库--->创建游标--->执行SQL--->fetch获得数据,进行业务处理--->关闭游标--->commit--->关闭数据库连接
1、基本使用
import pymysql
user=input('用户名: ').strip()
pwd=input('密码: ').strip()
#链接
conn=pymysql.connect(host='localhost',user='root',password='123456',database='test',charset='utf8')
#游标
cursor=conn.cursor() #执行完毕返回的结果集默认以元组显示
#配置结果集为字典形式
#cursor=conn.cursor(cursor=pymysql.cursors.DictCursor)
#执行sql语句
sql='select * from user where username="%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('登录失败')
2、sql注入
我们大家都知道:-- 是sql的注释,语法为: -- sql语句
假如我(用户名存在的情况):
用户名输入: lqz“ -- lqz zhuru
密码输入:123
显示结果如下:
或者我(用户名不存在的情况):
用户名输入: liuqz“ -- lqz zhuru
密码输入:123
显示结果如下:
#用户存在,绕过密码 select * from user where username="lqz" -- lqz zhuru" and password="123" #用户不存在,直接绕过: select * from user where username="liuqz" or 1=1 -- lqz zhuru" and password="123" #-- 是注释掉后面的sql,有什么也不会执行 # or 1=1 永远成立 #这样就绕过了用户名密码验证,就是我们常说的sql注入