先建立远程账户并授权
grant all on *.* to 'root'@'%'identified by '123';
flush privileges;
# 刷新
mysql模块基本使用
import pymysql
user = input('用户名: ').strip()
pwd = input('密码: ').strip()
conn = pymysql.connect(
host='192.168.31.80',
port=3306,
user='root',
password='123',
db='luffy',
charset='utf8'
)
# 拿到游标
cursor = conn.cursor()
# 执行sql语句
sql = 'select * from userinfo where user="%s" and pwd="%s"' % (user, pwd)
# 不用这招,会导致sql注入问题
rows = cursor.execute(sql)
cursor.close()
conn.close()
# 进行判断
if rows:
print('登陆成功')
else:
print('登陆失败')
execute()之sql注入
根本原理:就根据程序的字符串拼接name='%s',我们输入一个xxx' -- haha,用我们输入的xxx加'在程序中拼接成一个判断条件name='xxx' -- haha'
最后那一个空格,在一条sql语句中如果遇到select * from t1 where id > 3 -- and name='egon';则--之后的条件被注释掉了
#1、sql注入之:用户存在,绕过密码
egon" -- 任意字符
#2、sql注入之:用户不存在,绕过用户与密码
xxx" or 1=1 -- 任意字符
解决方法
import pymysql
user = input('用户名: ').strip()
pwd = input('密码: ').strip()
conn = pymysql.connect(
host='127.0.0.1',
port=3306,
user='root',
password='123',
db='luffy',
charset='utf8'
)
# 拿到游标
cursor = conn.cursor()
# 执行sql语句
sql = 'select * from userinfo where user=%s and pwd=%s'
# %s 去掉引号,pymysql会自动添加
rows = cursor.execute(sql, [user, pwd])
cursor.close()
conn.close()
# 进行判断
if rows:
print('登陆成功')
else:
print('登陆失败')
pymysql增删改
import pymysql
conn = pymysql.connect(
host='127.0.0.1',
port=3306,
user='root',
password='123',
db='luffy',
charset='utf8'
)
# 拿到游标
cursor = conn.cursor()
sql = 'insert into userinfo(user, pwd) values(%s, %s)'
rows = cursor.execute(sql, ('test', '111')) # 插一条
# rows = cursor.executemany(sql, [('yxx', '123'), ('egon1', '12345')])
# 插多条记录
print(rows)
print(cursor.lastrowid) # 最后一个插入的id
conn.commit()
cursor.close()
conn.close()
sql之查询
import pymysql
# 建立链接
conn=pymysql.connect(
host='127.0.0.1',
port=3306,
user='root',
password='123',
db='luffy',
charset='utf8'
)
# 拿游标
cursor = conn.cursor(pymysql.cursors.DictCursor) # cursor以字典形式
rows = cursor.execute('select * from userinfo')
# print(rows)
# print(cursor.fetchmany(2))
# res1 = cursor.fetchone()
# res2 = cursor.fetchone()
# res3 = cursor.fetchone()
# res4 = cursor.fetchone()
# print(res1)
# print(res4)
cursor.scroll(3, mode='absolute') # 相对绝对位置移动
cursor.scroll(3, mode='relative') # 相对当前位置移动
res5 = cursor.fetchone()
print(res5)
cursor.close()
conn.close()