pymysql 模块

安装

pip3 install pymysql

链接,执行sql,关闭(游标)

import pymysql
user= input('用户名:>>').strip()
pwd= input('密码:>>').strip()# 先链接,拿到游标
conn=pymysql.connect(host='localhost',user='root',password='123456',database='day47',charset='utf8')
cursor=conn.cursor()   # 拿到游标,即mysql >
# 执行sql
sql='select * from user where user="%s" and password="%s";'%(user,pwd)
print(sql)   # 注意%s需要加双引号
rows = cursor.execute(sql)    # 拿到受影响的行数

cursor.close()
conn.close()if rows:print('登录成功')
else:print('登录失败')

execute()之sql注入

原理

  符号--会注释掉它之后的sql,正确的语法:--后至少有一个任意字符

现象 

最后那一个空格,在一条sql语句中如果遇到select *
from t1 where id > 3 -- and name='egon';则--之后的条件被注释掉了#1、sql注入之:用户存在,绕过密码
egon' -- 任意字符#2、sql注入之:用户不存在,绕过用户与密码
xxx' or 1=1 -- 任意字符

解决方式 

# 原来是我们对sql进行字符串拼接
# sql="select * from userinfo where name='%s' and password='%s'" %(user,pwd)
# print(sql)
# rows=cursor.execute(sql)#改写为(execute帮我们做字符串拼接,我们无需且一定不能再为%s加引号了)
sql="select * from userinfo where name=%s and password=%s" # 注意%s需要去掉引号,因为pymysql会自动为我们加上
rows=cursor.execute(sql,[user,pwd]) #pymysql模块自动帮我们解决sql注入的问题,只要我们按照pymysql的规矩来。

增、批量增删、改:conn.commit()

import pymysql
先链接,拿到游标
conn=pymysql.connect(host='localhost',user='root',password='123456',database='day47')
cursor=conn.cursor() #拿到游标,即mysql >
#执行sql   增:
sql='insert into user1(user,password) VALUES (%s,%s)'
print(sql)
# rows = cursor.execute(sql,('xixi',123))  #插入一条记录
rows = cursor.executemany(sql,[('xixi',123),('aaa',456),('ttt',147)]) #插入多行记录
print('%s row in set (0.00 sec)'%rows)conn.commit() #提交到数据库
cursor.close()
conn.close()

批量增加

# coding:utf-8
import pymysql# 打开数据库连接
db = pymysql.connect(host='localhost', port=3306,user='username', passwd='password', db='database_name', charset='utf8')# 使用cursor()方法获取操作游标
cursor = db.cursor()# SQL 插入语句
sql = "INSERT INTO EMPLOYEE(FIRST_NAME, AGE, SEX) VALUES (%s,%s,%s)"
# 一个tuple或者list
T = (('xiaoming', 31, 'boy'), ('hong', 22, 'girl'), ('wang', 90, 'man'))try:# 执行sql语句
    cursor.executemany(sql, T)# 提交到数据库执行
    db.commit()
except :# 如果发生错误则回滚
    db.rollback()
# 关闭游标
cursor.close()
# 关闭数据库连接
db.close()

import pymysql
#先链接,拿到游标
name=input('>>').strip()
conn=pymysql.connect(host='localhost',user='root',password='123456',database='day47')
cursor=conn.cursor() #拿到游标,即mysql >
#执行sql   删:
sql='delete from user1 where user =%s;'  #删除数据
print(sql)
rows = cursor.execute(sql,(name))
print('%s row in set (0.00 sec)'%rows)conn.commit() #提交到数据库
cursor.close()
conn.close()

import pymysql
#先链接,拿到游标
id=input('>>').strip()
conn=pymysql.connect(host='localhost',user='root',password='123456',database='day47')
cursor=conn.cursor() #拿到游标,即mysql >
#执行sql   改:
sql=' update user1 set password = "5555555" where id=%s;'
print(sql)
rows = cursor.execute(sql,(id))
print('%s row in set (0.00 sec)'%rows)conn.commit() #提交到数据库
cursor.close()
conn.close()

查:fetchone,fetchmany,fetchall

# ---------查fetchone,fetchmany,fetchall-----------
import pymysql
conn=pymysql.connect(host='localhost',user='root',password='123456',database='day47')
cursor=conn.cursor() #拿到游标,即mysql >
#执行sql   查:
sql='select * from user1;'
rows = cursor.execute(sql)#查单条fetchone
res1=cursor.fetchone()
res2=cursor.fetchone()
res3=cursor.fetchone()
print(res1)
print(res2)
print(res3)
print(res3[0])#查多条fetchmany
print(cursor.fetchmany(3))
print(cursor.fetchone())#查所有fetchall
print(cursor.fetchall())
print(cursor.fetchone())#-------光标的移动--------
#1.绝对路径:从文件的开头位置算起
print(cursor.fetchall())
cursor.scroll(1,mode='absolute')
print(cursor.fetchone())
cursor.scroll(3,mode='absolute')
print(cursor.fetchone())#2.相对路径:
print(cursor.fetchone())
print(cursor.fetchone())
cursor.scroll(2,mode='relative') #相对于上面的两条向后移两条
print(cursor.fetchone())print('%s row in set (0.00 sec)' %rows)
cursor.close()
conn.close()

获取插入的最后一条数据的自增ID

------查看表中最后一行的iD
import pymysql
conn=pymysql.connect(host='localhost',user='root',password='123456',database='day47',charset='utf8')
cursor=conn.cursor()sql='insert into user1(user,password) values(%s,%s);'
rows=cursor.execute(sql,('alex','123'))
# rows=cursor.executemany(sql,[('yuanhao','123'),('laowu','123'),('kgf','12323')])
conn.commit()
print(cursor.lastrowid)  #查看表中最后一行的iD

cursor.close()
conn.close()

异步处理

# 用twisted库将数据进行异步插入到数据库import pymysql
from twisted.enterprise import adbapi
from twisted.internet import reactorclass MysqlTwistedPipeline(object):def __init__(self, dbpool):self.dbpool = dbpool@classmethoddef from_settings(cls, settings):# 需要在setting中设置数据库配置参数dbparms = dict(host=settings['MYSQL_HOST'],db=settings['MYSQL_DBNAME'],user=settings['MYSQL_USER'],passwd=settings['MYSQL_PASSWORD'],charset='utf8',cursorclass=pymysql.cursors.DictCursor,use_unicode=True,)# 连接ConnectionPool(使用MySQLdb连接,或者pymysql)dbpool = adbapi.ConnectionPool("MySQLdb", **dbparms)  # **让参数变成可变化参数return cls(dbpool)  # 返回实例化对象def process_item(self, item, spider):# 使用twisted将MySQL插入变成异步执行query = self.dbpool.runInteraction(self.do_insert, item)# 添加异常处理
        query.addCallback(self.handle_error)def handle_error(self, failure):# 处理异步插入时的异常print(failure)def do_insert(self, cursor, item):# 执行具体的插入insert_sql = """insert into jobbole_artitle(name, base_url, date, comment)VALUES (%s, %s, %s, %s)"""cursor.execute(insert_sql, (item['name'], item['base_url'], item['date'], item['coment'],))

转载于:https://www.cnblogs.com/shijieli/p/10344671.html

5.15 pymysql 模块相关推荐

  1. MySQL -Naivacat工具与pymysql模块

    Navicat 在生产环境中操作MySQL数据库还是推荐使用命令行工具mysql,但在我们自己开发测试时,可以使用可视化工具Navicat,以图形界面的形式操作MySQL数据库. 官网下载:https ...

  2. python 全栈开发,Day63(子查询,MySQl创建用户和授权,可视化工具Navicat的使用,pymysql模块的使用)...

    昨日内容回顾 外键的变种三种关系:多对一:左表的多 对右表一 成立左边的一 对右表多 不成立foreign key(从表的id) refreences 主表的(id)多对多建立第三张表(foreign ...

  3. Python中操作mysql的pymysql模块详解

    前言 pymsql是Python中操作MySQL的模块,其使用方法和MySQLdb几乎相同.但目前pymysql支持python3.x而后者不支持3.x版本. 本文测试python版本:2.7.11. ...

  4. python的mysql模块_Python中操作mysql的pymysql模块详解

    前言 pymsql是Python中操作MySQL的模块,其使用方法和MySQLdb几乎相同.但目前pymysql支持python3.x而后者不支持3.x版本. 本文测试python版本:2.7.11. ...

  5. 多表查询,初识pymysql模块

    一. 多表连接查询 外链接语法 select 字段列表from 表1 (inner\left\right) join 表2on 表1.字段 = 表2.字段; 1 #建表 2 #部门表 3 create ...

  6. pymysql模块和SQL注入

    目录 1.sql复习和分表操作 2.pymysql模块 2.1 pymysql的使用步骤 2.1 pymysql 增删改 1.数据提交和数据回滚 3.sql注入 1. 什么是SQL注入 2.非安全方式 ...

  7. Python进阶----pymysql模块的使用,单表查询

    Python进阶----pymysql模块的使用,单表查询 一丶使用pymysql ​   ​   1.下载pymysql包: pip3 install pymysql ​​   ​   2.编写代码 ...

  8. 05 数据库入门学习-正则表达式、用户管理、pymysql模块

    一.正则表达式 正则表达式用于模糊查询,模糊查询已经讲过了  like 仅支持 % 和 _ 远没有正则表达式灵活 当然绝大多数情况下 like足够使用 #语法 select *from table w ...

  9. Day42-数据库入门学习-正则表达式、用户管理、pymysql模块

    一.正则表达式 正则表达式用于模糊查询,模糊查询已经讲过了 like 仅支持 % 和 _ 远没有正则表达式灵活 当然绝大多数情况下 like足够使用 #语法 select *from table wh ...

最新文章

  1. 计算机视觉:值得一读的五本计算机视觉教科书
  2. 2.4带通采样的实际问题
  3. matlab怎么安装compiler,关于MATLAB中compiler配置问题
  4. 学java要学vue吗_学vue之前必看
  5. MAC地址和IP地址的关系
  6. .Net 平台下的版本控制 --- Subversion(SVN)1.6.x
  7. 设置文件为源文件(和src一样)
  8. 二扩域元素与整数的转换
  9. bzoj 3123 [Sdoi2013]森林
  10. uva 12086 树状数组
  11. 使用Directshow + LAVFilter做一个万能格式的多媒体播放器
  12. 网站木马修复网站漏洞修复方案
  13. python求txt文件内平均值_如何使用python计算几个.dat文件的平均值?
  14. Prometheus+Grafana监控
  15. python中tell_Python中tell()方法的使用详解
  16. 移动互联网终端的touch事件,touchstart, touchend, touchmove
  17. 融云CEO董晗:国产化进程加速,助推政企数智办公平台深化发展
  18. 【系统集成项目管理工程师】—关键路径
  19. python程序运行时间计时
  20. 老雷:思儿壮志小诗一首(老爸写得都比我好,让我这个文艺青年情何以堪)(家人对幸福美好生活的追求,就是我的奋斗目标)...

热门文章

  1. 使用 jetty-maven-plugin发布maven项目
  2. Loadrunner脚本学习总结
  3. Callable、Future和FutureTask
  4. 阿里古谦:阿里互联网架构的6大最佳实践-博客-云栖社区-阿里云
  5. 网页主动探测工具使用
  6. MPEG简介 + 如何计算CBR 和VBR的MP3的播放时间
  7. [转载] C#面向对象设计模式纵横谈——12. Flyweight享元模式
  8. DKHadoop人力资源大数据解决方案架构
  9. 11:菜单自动化软件部署经典案例
  10. 服务器宽带性能如何?----internet性能测试站点汇集