pymysql模块初见

时间:2019-08-22
本文章向大家介绍pymysql模块初见,主要包括pymysql模块初见使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

一.pymysql的基本使用方法

import pymysql

db = pymysql.connect(
    host = '127.0.0.1',
    port = 3306,
    user = 'root',
    password = '123',
    database = 'day36',
    charset = 'utf8',
# 写成了utf-8会直接报错
    autocommit = True
# 这个参数配置完成后  增删改操作都不需要在手动加conn.commit了
)

# cursor = db.cursor()
# 产生一个游标对象  以元组的形式进行返回
cursor = db.cursor(pymysql.cursors.DictCursor)
# 产生一个游标对象  以字典的形式返回查询出来的数据 键是表的字段  值是表的字段对应的信息

sql = 'select * from emp'

res = cursor.execute(sql)
# 使用 execute() 方法执行 SQL,返回值是查询到的数据条数
print(res)
if res:
    # print(cursor.fetchone())
    # 获取一条数据,返回值字典
    # cursor.scroll(0,'absolute')
    #控制光标移动,相对于起始位置,往后移动多少
    # cursor.scroll(1,'relative')
    # 基于当前光标的位置,正数向后移动,负数向前移动
    # print(cursor.fetchall())
    #获取所有数据,返回值列表套字典
    print(cursor.fetchmany())
    # 不加参数返回一条,加了返回指定条数
else:
    print('error')
db.close()
View Code

ps:想要获取增删改的权限,需要在execute之后添加conn.commit提交

二.sql注入问题

import pymysql

db = pymysql.connect(
    host = '127.0.0.1',
    port = 3306,
    user = 'root',
    password = '123',
    database = 'day36',
    charset = 'utf8',
# 写成了utf-8会直接报错
    autocommit = True
# 这个参数配置完成后  增删改操作都不需要在手动加conn.commit了
)

# cursor = db.cursor()
# 产生一个游标对象  以元组的形式进行返回
cursor = db.cursor(pymysql.cursors.DictCursor)
# 产生一个游标对象  以字典的形式返回查询出来的数据 键是表的字段  值是表的字段对应的信息


name = input(">>:").strip()
sex=  input(">>:").strip()
sql = 'select * from emp where name="%s"and sex="%s"' %(name,sex)
print(sql)
res = cursor.execute(sql)
# 使用 execute() 方法执行 SQL,返回值是查询到的数据条数
print(cursor.fetchall())
# sql注入 就是利用注释等具有特殊意义的符号 来完成一些骚操作
#
# 后续写sql语句  不要手动拼接关键性的数据
# res = cursor.execute(sql,(name,sex))
# 而是让excute帮你去做拼接
View Code

原文地址:https://www.cnblogs.com/Cpsyche/p/11397422.html