import pymysql #连接mysql数据库
client = pymysql.connrct(host = 'ip',port = 端口,user = '用户名',password = '密码',database='库名',charset='字符编码',autocommit =True)
#获取游标对象:游标可以用来提交sql命令
cursor_obj = client.cursor(pymysql.cursors.DictCursor)
#通过execute可以提交sql语句
sql = 'select * from emp'
cursor_obj.execute(sql)
#提交后可以通过cursor_obj对象.fetchall()获取可以查询到的结果
res = cursor_obj.fetchall()
print(res)
for dic in res:
print(dic)
#关闭游标
curcor_obj.close()
import pymysql
conn = pymysql.connect(
user = 'root', 用户名
password = '12345', 用户密码
host = '127.0.0.1', 服务端ip
port = 3306, 服务端端口
charset = 'utf8', 字符编码
database = 'db2') 访问具体的库
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)#将查询到的结果制作成字典形式返回
# sql = "select * from user"
# res = cursor.execute(sql)
# # print(res)
# # print(cursor.fetchall())#打印全部的信息
# # cursor.scroll(1,'relative')#相对偏移度基于指针所在的位置往后偏移
# cursor.scroll(1,'absolute')#基于起始位置往后偏移
# print(cursor.fetchall())
while True:
username = input(':').strip()
password = input(':').strip()
sql = "select * from user where name ='%s' and password ='%s'"
print(sql)
cursor.execute(sql, (username, password))#提交sql语句解决注入问题
res = cursor.fetchall()
if res:
print(res)
break
else:
print('username or password error')
continue
#增加
sql = 'insert into user(name,password)values("jssss",123)'
#修改
# sql = 'update user set name="sss" where id = 2'
#删除
# sql = 'delete from user where id = 1'
res = cursor.execute(sql)
print(res)
conn.commit() #提交到内核中
#所谓注入问题就是利用特殊符号和注释语法巧妙的绕过真正的sql验证
# 如 用户名‘ __ sssss 直接回车可以免密登陆
#关键性的数据不要自己手动拼接而是交由execute帮你做拼接