Python pymysql模块

pymysql模块

1.什么是pymysql:PyMySQL 是在 Python3.x 版本中用于连接 MySQL 服务器的一个库,Python2中则使用mysqldb。

2.pymysql模块是第三方的需要自己安装:

# 1.安装:pip3 insatll pymysql
安装pynysql库

3.基本语法使用

# 导入pymysql模块
import pymysql

# 连接到数据库
conn = pymysql.connect(
    host = '127.0.0.1', # 数据库ip地址
    port = 3306, # 数据库端口号
    user = 'root', # 用户名
    password = '123', # 密码
    database = 'day38', # 数据库
    charset = 'utf8',  # 编码千万不要加- 如果写成了utf-8会直接报错
    autocommit = True  # 这个参数配置完成后  增删改操作都不需要在手动加conn.commit()了
)

# 产生游标对象
cursor = conn.cursor(pymysql.cursors.DictCursor)  # 产生一个游标对象 每行数据 以字典的形式或列表套元组展现 键是表的字段名  值是表的字段值,不设置查询结果解释元组或元组套元组

# sql语句拼接
sql = sql语句  # 例:# sql = 'insert into user(name,password) values("jerry","666")'

# 执行sql语句,sql注入和sql语句拼接后续再讲
res = cursor.execute(sql) # 
# cursor.excutemany(sql,[(),(),()] # 一次插入多行记录

# 获取结果
# res = cursor.fetchone() # 获取一条数据
# res = cursor.fetchmany(10) # 获取10条数据,参数可修改
res = cursor.fetchall()  # 获取所有结果 游标设置的话是列表里面套字典

# 关闭
cursor.close() # 关闭游标
conn.close() # 关闭连接

# 补充:
cursor.scroll(2,'absolute')  # 控制光标移动   absolute相对于其实位置 往后移动几位,参数可修改
cursor.scroll(1,'relative')  # relative相对于当前位置 往后移动几位,参数可修改
pymysql基本语句

4.sql注入

1.什么是sql注入:太过于相信用户输入的信息,用户利用注释等具有特殊意义的符号 来完成有漏洞的sql语句。

2.解决办法:后续写sql语句 不要手动拼接关键性的数据,而是让excute帮你去做拼接

3.案例:

conn = pymysql.connect(
    host = '127.0.0.1',
    port = 3306,
    user = 'root',
    password = '123',
    database = 'day38',
    charset = 'utf8',  # 编码千万不要加- 如果写成了utf-8会直接报错
    autocommit = True  # 这个参数配置完成后  增删改操作都不需要在手动加conn.commit()了
)
cursor = conn.cursor(pymysql.cursors.DictCursor)  # 产生一个游标对象  以字典的形式返回查询出来的数据 键是表的字段  值是表的字段对应的信息

username = input('username>>>:')
password = input('password>>>:')
# 注入问题
'''
sql = "select * from user where name =%s and password = %s" % (username,password)
cursor.execute(sql) 
'''
# 解决方法
sql = "select * from user where name =%s and password = %s"
res = cursor.execute(sql,(username,password))  # 能够帮你自动过滤特殊符号 避免sql注入的问题,execute 能够自动识别sql语句中的%s 帮你做替换,res是结果的数量整型

 if res:
     print(cursor.fetchall())
 else:
     print('用户名或密码错误')
sql注入
#
sql = "insert into user(username,password) values(%s,%s)"
rows = cursor.excute(sql,('jason','123'))

# 修改
sql = "update user set username='jasonDSB' where id=1"
rows = cursor.excute(sql)

"""
增和改单单执行excute并不会真正影响到数据,需要再执行conn.commit()才可以完成真正的增改
"""

# 一次插入多行记录
res = cursor,excutemany(sql,[(),(),()]
View Code

 

posted @ 2019-08-22 16:52  心慌得初夏  阅读(255)  评论(0编辑  收藏  举报
levels of contents