主要内容:
一、pymysql模块的使用
二、pymysq模块增删改查
1️⃣ pymsql模块的使用
1、前言:之前我们都是通过MySQL自带的命令行客户端工具mysql来操作数据库,
那如何在python程序中操作数据库呢?这就用到了pymysql模块,该模块本质就是一个套接字
客户端软件,使用前需要事先安装。
pip3 install pymysql
2、实例:
#!/user/bin/env python3
# -*- coding:utf-8-*-
# write by congcong
import pymysql
user = input('user>>:').strip()
pwd = input('password>>:').strip()
# 建立链接
conn=pymysql.connect(
host='127.0.0.1',
port=3306,
user='root',
password='0514',
db='db6',
charset='utf8'
)
# 拿到游标
cursor = conn.cursor() # 执行完毕后返回的结果集默认以元祖显示
# 执行sql语句
sql = 'select * from userinfo where name="%s" and pwd="%s"' %(user,pwd)
print(sql)
rows = cursor.execute(sql) # 受影响的行数,execute表示执行
cursor.close() # 关闭游标
conn.close() # 关闭链接
if rows:
print('登陆成功!')
else:
print('失败...')
注意:
这种方式存在很大的隐患,即sql注入问题,可绕过密码登录,如:cc1" -- hello
3、execute()之sql注入
注意:符号--会注释掉它之后的sql,正确的语法:--后至少有一个任意字符
user>>:cc1" -- hello # “ 对应左边的左引号,”--“ 在sql语句中表示注释后面的语句,注意中间有空格
password>>:
select * from userinfo where name="cc1" -- hello" and pwd=""
登陆成功!
# 甚至可同时绕过用户名和密码,如:xxxx" or 1=1 -- hello
'''
user>>:xxx" or 1=1 -- hello # or表示或,用户名满足任意一条件即可
password>>:
select * from userinfo where name="xxx" or 1=1 -- hello" and pwd=""
登陆成功!
'''
上述程序的改进版如下:
#!/user/bin/env python3
# -*- coding:utf-8-*-
# write by congcong
import pymysql
# 改进版如下:
user = input('用户名>>:').strip()
pwd = input('密码>>:').strip()
# 建立链接
conn = pymysql.connect(
host='localhost',
port= 3306,
user = 'root',
password = '0514',
db='db6',
charset = 'utf8'
)
# 拿到游标
cursor = conn.cursor()
# 执行
sql = 'select * from userinfo where name=%s and pwd=%s'
# print(sql)
rows = cursor.execute(sql,(user,pwd))
cursor.close()
conn.close()
if rows:
print('welcome login!')
else:
print('failed...')