navicat工具
生产环境还是推荐使用mysql命令行,但为了方便我们测试,可以使用IDE工具.
下载链接:https://pan.baidu.com/s/1bpo5mqj
Pymysql模块
在python代码中连接mysql数据库并使用sql语句,是框架ORM实现的基础.
import pymysql
user = input('用户名>>> ').strip()
pwd = input('密码>>> ').strip()
# 连接数据库
conn=pymysql.connect(host='localhost',user='root', passwd='abc123',db="login",charset='utf8')
cursor = conn.cursor()
sql = 'select * from userinfo WHERE username="%s" and password="%s";' % (user, pwd)
try:
rows = cursor.execute(sql) # 执行sql语句并拿到受影响的行数
print(sql)
if rows:
print('欢迎登陆!')
else:
print('用户名或密码不正确!')
except Exception as e:
print(e)
cursor.close()
conn.close()
在对数据库进行增删改操作后,必须提交conn.commit()
才生效.
取出结果:ret = cursor.fetchone()
取出一行记录;rets = cursor.fetchall()
取出所有记录,每一行结果以是以元祖形式.
后台sql注入问题
在sql语句中,--
后的内容为注释,利用这个可以实现无密码登录或无须用户名直接登录.
# 免密码登录
用户名>>> bob" -- asas
密码>>>
select * from user WHERE username="kate" -- asas" and password="";
欢迎登陆!
# 免用户名登录
用户名>>> xxx" or 1=1 -- as
密码>>>
select * from user WHERE username="xxx" or 1=1 -- as" and password="";
欢迎登陆
解决办法:
sql = 'select * from user WHERE username=%s and password=%s;'
rows = cursor.execute(sql, [user, pwd])
pymysql中文乱码
在window上出现解决办法:
进入\Python36\Lib\site-packages\pymysql\connections.py
文件下下,修改如下: