pymysql 模块

安装

pip3 install pymysql

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

import pymysql
user= input('用户名:>>').strip()
pwd= input('密码:>>').strip() # 先链接,拿到游标
conn=pymysql.connect(host='localhost',user='root',password='',
             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='',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='',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='',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='',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='',
             database='day47',charset='utf8')
cursor=conn.cursor() sql='insert into user1(user,password) values(%s,%s);'
rows=cursor.execute(sql,('alex',''))
# 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 reactor class MysqlTwistedPipeline(object):
def __init__(self, dbpool):
self.dbpool = dbpool @classmethod
def 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'],))

5.15 pymysql 模块的更多相关文章

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

    Python中操作mysql的pymysql模块详解 前言 pymsql是Python中操作MySQL的模块,其使用方法和MySQLdb几乎相同.但目前pymysql支持python3.x而后者不支持 ...

  2. python实战第一天-pymysql模块并练习

    操作系统 Ubuntu 15.10 IDE & editor JetBrains PyCharm 5.0.2 ipython3 Python版本 python-3.4.3 安装pymysql模 ...

  3. python 存储引擎 mysql(库,表, 行) 单表多表操作 (foreign key) sql_mode pymysql模块讲解

    ##################总结############### mysql 常用数据类型 整型:tinyint  int(42亿条左右)  bigint 小数:float double dec ...

  4. (转)Python中操作mysql的pymysql模块详解

    原文:https://www.cnblogs.com/wt11/p/6141225.html https://shockerli.net/post/python3-pymysql/----Python ...

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

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

  6. 第八章| 3. MyAQL数据库|Navicat工具与pymysql模块 | 内置功能 | 索引原理

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

  7. mysql python pymysql模块 基本使用

    我们都是通过MySQL自带的命令行客户端工具mysql来操作数据库,那如何在python程序中操作数据库呢? 这就用到了pymysql模块,该模块本质就是一个套接字客户端软件,使用前需要事先安装 pi ...

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

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

  9. pymysql模块使用---Python连接MySQL数据库

    pymysql模块使用---Python连接MySQL数据库 浏览目录 pymysql介绍 连接数据库 execute( ) 之 sql 注入 增删改查操作 进阶用法 一.pymysql介绍 1.介绍 ...

随机推荐

  1. WebGIS中以version方式实现代码更新后前端自动读取更新代码的方法

    文章版权由作者李晓晖和博客园共有,若转载请于明显处标明出处:http://www.cnblogs.com/naaoveGIS/ 1. 前言 GIS代码进行更新后,由于用户前端已有缓存,导致更新的功能不 ...

  2. iOS----------viewcontroller中的dealloc方法不调用

    ios的viewcontroller生命周期是 init -> loadView -> viewDidLoad -> viewWillAppear -> viewDidAppe ...

  3. Android 常驻广播和非常驻广播

    一.知识准备 ①常驻广播接受者:使用AndroidManifest.xml注册,接受者不随Activity的销毁而销毁,也就是拥有独立的生命周期. ②非常驻广播接受者:使用registerReceiv ...

  4. QT多线程的使用

    今天给大家介绍三种QT里面使用多线程的方法 1.继承QThread并且重写run方法来实现多线程 #ifndef MYQTHREAD_H #define MYQTHREAD_H #include &l ...

  5. 使用Connector/C++(VS2015)连接MySQL的完整例子

    完整示例代码1 /* Copyright 2008, 2010, Oracle and/or its affiliates. All rights reserved. This program is ...

  6. web-garden 和 web-farm 有什么不同 ?

    相同:都是网络托管系统. 不同: web-garden:是在单个服务器包含许多处理器的设置: web-farm:是使用多个服务器的较大设置.

  7. Clickhouse v18编译记录

    简介 ClickHouse是"战斗民族"俄罗斯搜索巨头Yandex公司开源的一个极具"战斗力"的实时数据分析数据库,是面向 OLAP 的分布式列式DBMS,圈内 ...

  8. oracle nvl2函数

    nvl2(v1, v2, v3) 定义:如果v1为空,返回v3: 不为空,返回v2 nvl2要求v2,v3的类型一致,不一致会发生类型转换.问题:最终返回值类型是v2的类型还是v3的类型? 看题目:n ...

  9. Docker之进入容器(三)

    1.简介 经过前面两篇博客的扫盲,大家多多少少对docker有了一个基本的了解,也接触了docker的常用命令.在这篇博客中,我将介绍进入docker容器的几种方式. 2.进入docker中的几种方式 ...

  10. Windows的GDI映射方式,逻辑坐标,设备坐标的理解

    最近在学Win32的编程,看的是<Windows程序设计第5版>一书,这本书是台湾人翻译的,有些译法和大陆不一样,书中还有一些错误的地方,很多时候需要中英文对照阅读,下载请点击 https ...