文章目录

  • mysql驱动模块connector的语法
  • SQL注入攻击案例
  • SQL预编译机制 防御SQL注入攻击
  • MySQLconnect异常处理
  • 数据库连接池
  • mysql connect删除数据
  • 实战:mysqlconnector模块综合使用

mysql驱动模块connector的语法

# -*- encoding: utf-8 -*-
"""
@File    : demo_1.py
@Time    : 2021-08-06 14:37
@Author  : XD
@Email   : gudianpai@qq.com
@Software: PyCharm
"""
import mysql.connector
con = mysql.connector.connect(host="localhost", port=3306,user="root", password="xd19970306",database="demo"
)con.close()#另外一种连接
import mysql.connector
config = {"host":"localhost","port":3306,"user":"root","password":"xd19970306","database":"demo"
}
con = mysql.connector.connect(**config)
print("finish!")#游标
cursor = con.cursor()
sql = "SELECT empno, ename, hiredate FROM t_emp;"
cursor.execute(sql)
for one in cursor:print(one[0], one[1], one[2])
finish!
7369 SMITH 1980-12-17
7499 ALLEN 1981-02-20
7521 WARD 1981-02-22
7566 JONES 1981-04-02
7654 MARTIN 1981-09-28
7698 BLAKE 1981-05-01
7782 CLARK 1981-06-09
7788 SCOTT 1982-12-09
7839 KING 1981-11-17
7844 TURNER 1981-09-08
7876 ADAMS 1983-01-12
7900 JAMES 1981-12-03
7902 FORD 1981-12-03
7934 MILLER 1982-01-23Process finished with exit code 0

SQL注入攻击案例

cursor.execute(sql%(username,password))
cursor.execute(sql,(username,password))
import mysql.connector
config={"host":"localhost","port":3306,"user":"root","password":"xd19970306","database":"vega"
}
con=mysql.connector.connect(**config)
username="1 OR 1=1"
password="1 OR 1=1"
sql="SELECT COUNT(*) FROM t_user WHERE username=%s " \"AND AES_DECRYPT(UNHEX(password),'HelloWorld')=%s"
cursor=con.cursor()
cursor.execute(sql%(username,password))
print(cursor.fetchone()[0])
con.close()

SQL预编译机制 防御SQL注入攻击

预编译也可以提升查询速度

import mysql.connector
config={"host":"localhost","port":3306,"user":"root","password":"xd19970306","database":"vega"
}
con=mysql.connector.connect(**config)
username="1 OR 1=1"
password="1 OR 1=1"
sql="SELECT COUNT(*) FROM t_user WHERE username=%s " \"AND AES_DECRYPT(UNHEX(password),'HelloWorld')=%s"
cursor=con.cursor()
cursor.execute(sql,(username,password))
print(cursor.fetchone()[0])
con.close()

MySQLconnect异常处理

# -*- encoding: utf-8 -*-
"""
@File    : demo_3.py
@Time    : 2021-08-09 10:20
@Author  : XD
@Email   : gudianpai@qq.com
@Software: PyCharm
"""
import mysql.connector
try:con=mysql.connector.connect(host="localhost",port=3306,user="root",password="xd19970306",database="demo")con.start_transaction()cursor=con.cursor()sql="INSERT INTO t_emp(empno,ename,job,mgr,hiredate,sal,comm,deptno) " \"VALUES(%s,%s,%s,%s,%s,%s,%s,%s)"cursor.execute(sql,(9680,"赵娜","SALESMAN",None,"1985-12-1",2500,None,10))con.commit()
except Exception as e:if "con" in dir():con.rollback()print(e)
finally:if "con" in dir():con.close()

数据库连接池


#数据库连接是一种关键的 有限的 昂贵的 资源,在并发执行的应用程序中体现的尤为重要
#应用程序<-TCP协议->数据库
#用数据库连接池解决这个问题
#预先创建出一些数据库连接,然后缓存起来,避免了重复创建销毁
import mysql.connector.pooling
config={"host":"localhost","port":3306,"user":"root","password":"xd19970306","database":"demo"
}
try:pool=mysql.connector.pooling.MySQLConnectionPool(**config,pool_size=10)con=pool.get_connection()#开启事务con.start_transaction()cursor=con.cursor()sql="UPDATE t_emp SET sal=sal+%s WHERE deptno=%s"cursor.execute(sql,(200, 20))con.commit()
except Exception as e:if "con" in dir():#回滚(就是返回初始状态)con.rollback()print(e)

mysql connect删除数据

# -*- encoding: utf-8 -*-
"""
@File    : demo_4.py
@Time    : 2021-08-09 13:55
@Author  : XD
@Email   : gudianpai@qq.com
@Software: PyCharm
"""
#数据库连接是一种关键的 有限的 昂贵的 资源,在并发执行的应用程序中体现的尤为重要
#应用程序<-TCP协议->数据库
#用数据库连接池解决这个问题
#预先创建出一些数据库连接,然后缓存起来,避免了重复创建销毁
import mysql.connector.pooling
config={"host":"localhost","port":3306,"user":"root","password":"xd19970306","database":"demo"
}
try:pool=mysql.connector.pooling.MySQLConnectionPool(**config,pool_size=10)con=pool.get_connection()#开启事务con.start_transaction()cursor=con.cursor()#sql="DELETE e, d FROM t_emp e JOIN t_dept d ON e.deptno=d.deptno WHERE d.detpno = 20"sql="DELETE e,d FROM t_emp e JOIN t_dept d ON e.deptno=d.deptno WHERE d.deptno=20"cursor.execute(sql)con.commit()
except Exception as e:if "con" in dir():#回滚(就是返回初始状态)con.rollback()print(e)

使用truncat

# -*- encoding: utf-8 -*-
"""
@File    : demo_4.py
@Time    : 2021-08-09 13:55
@Author  : XD
@Email   : gudianpai@qq.com
@Software: PyCharm
"""
#数据库连接是一种关键的 有限的 昂贵的 资源,在并发执行的应用程序中体现的尤为重要
#应用程序<-TCP协议->数据库
#用数据库连接池解决这个问题
#预先创建出一些数据库连接,然后缓存起来,避免了重复创建销毁
import mysql.connector.pooling
config={"host":"localhost","port":3306,"user":"root","password":"xd19970306","database":"demo"
}
try:pool=mysql.connector.pooling.MySQLConnectionPool(**config,pool_size=10)con=pool.get_connection()#开启事务#con.start_transaction()cursor=con.cursor()#sql="DELETE e, d FROM t_emp e JOIN t_dept d ON e.deptno=d.deptno WHERE d.detpno = 20"#truncate 不依赖于事务机制   sql = "TRUNCATE TABLE t_emp"cursor.execute(sql)#con.commit()
except Exception as e:if "con" in dir():#回滚(就是返回初始状态)con.rollback()print(e)

反复执行

#反复执行 excutemany()
import mysql.connector.pooling
config = {"host":"localhost","port":3306,"user":"root","password":"xd19970306","database":"demo",
}
try:pool = mysql.connector.pooling.MySQLConnectionPool(**config,pool_size = 10)con = pool.get_connection()con.start_transaction()cursor = con.cursor()sql = "INSERT INTO t_dept(deptno, dname, loc) VALUES(%s, %s, %s)"data = [[100,"A部门","北京"],[110,"B部门","上海"]]cursor.executemany(sql,(data))con.commit()
except Exception as e:if "con" in dir():#回滚(就是返回初始状态)con.rollback()print(e)

实战:mysqlconnector模块综合使用

# -*- encoding: utf-8 -*-
"""
@File    : demo_7.py
@Time    : 2021-08-09 22:28
@Author  : XD
@Email   : gudianpai@qq.com
@Software: PyCharm
"""
import mysql.connector.pooling
config = {"host":"localhost","port":3306,"user":"root","password":"xd19970306","database":"demo",
}
try:pool = mysql.connector.pooling.MySQLConnectionPool(**config,pool_size = 10)con = pool.get_connection()con.start_transaction()#ddl语句 不受事务机制影响cursor = con.cursor()#创建新表并且复制数据#sql = "CREATE TABLE t_emp_new AS (SELECT * FROM t_emp)"#单纯创建表结构sql = "DROP TABLE t_emp_new"cursor.execute(sql)sql = "CREATE TABLE t_emp_new LIKE t_emp"cursor.execute(sql)sql = "SELECT AVG(sal) AS avg FROM t_emp"cursor.execute(sql)temp = cursor.fetchone()avg = temp[0]sql = "SELECT deptno FROM t_emp GROUP BY deptno HAVING AVG(sal)>=%s"cursor.execute(sql, [avg])#print(cursor.fetchone()[0])#print(cursor.fetchall())# for one in cursor:#     print(one[0])temp = cursor.fetchall()sql = "INSERT INTO t_emp_new SELECT * FROM t_emp WHERE deptno IN ("for index in range(len(temp) - 1):one = temp[index][0]sql += str(one) + ","sql += str(temp[-1][0])sql += ")"print(sql)cursor.execute(sql)sql = "DELETE FROM t_emp WHERE deptno IN ("for index in range(len(temp) - 1):one = temp[index][0]sql += str(one) + ","sql += str(temp[-1][0])sql += ")"cursor.execute(sql)sql = "SELECT deptno FROM t_dept WHERE dname=%s"cursor.execute(sql, ['SALES'])deptno = cursor.fetchone()[0]sql = "UPDATE t_emp_new SET deptno=%s"cursor.execute(sql,[deptno])con.commit()
except Exception as e:if "con" in dir():#回滚(就是返回初始状态)con.rollback()print(e)

# -*- encoding: utf-8 -*-
"""
@File    : demo_8.py
@Time    : 2021-08-10 2:17
@Author  : XD
@Email   : gudianpai@qq.com
@Software: PyCharm
"""
import mysql.connector.pooling
config = {"host":"localhost","port":3306,"user":"root","password":"xd19970306","database":"demo",
}
try:pool = mysql.connector.pooling.MySQLConnectionPool(**config,pool_size=10)con = pool.get_connection()con.start_transaction()sql = "INSERT INTO t_dept (SELECT MAX(deptno)+10,%s,%s FROM t_dept UNION SELECT MAX(deptno)+20,%s,%s FROM t_dept)"cursor=con.cursor()cursor.execute(sql,("C部门","西安","D部门","广州"))con.commit()
except Exception as e:if "con" in dir():#回滚(就是返回初始状态)con.rollback()print(e)
10   ACCOUNTING  NEW YORK
20  RESEARCH    DALLAS
30  SALES   CHICAGO
40  OPERATIONS  BOSTON
50  A部门 北京
60  B部门 上海

note

#不能既在一个数据表中查询数据,又写入数据。
#You can't specify target table 't_dept' for update in FROM clause
#多条查询语句会遇到上述情况
INSERT INTO t_dept(deptno, dname, loc)
VALUES((SELECT MAX(deptno) FROM t_dept)
+ 10,
"A部门","北京")
#调整
INSERT INTO t_dept
(SELECT MAX(deptno)+10,"A部门",
"北京" FROM t_dept UNION
SELECT MAX(deptno)+20,"B部门",
"上海" FROM t_dept
)

08Mysql与python交互相关推荐

  1. mongodb和python交互

    mongodb和python交互 1. mongdb和python交互的模块 pymongo 提供了mongdb和python交互的所有方法 安装方式: pip install pymongo 2. ...

  2. MySQL和Python交互

    与Python交互 python3模块名:pymysql conda install pymysql conda install sqlalchemy python2模块名:MySQLdb impor ...

  3. android与python交互_Android与Python混合编程

    前言 早在2017年的时候,出于业余兴趣,我就开始研究关于Python移植到Android上的实现方案,我一直希望能实现Android与Python的混合编程,并为此写了一系列博客,我希望借助JNI技 ...

  4. 【Python】学习笔记总结9(数据库与Python交互)

    文章目录 九.数据库与Python交互 1.连接MYSQL数据库 1.1.创建表 1.2.插入数据 1.3.查询数据 1.4.更新数据 1.5.删除数据 1.6.执行事务 1.7.读取数据库表数据并写 ...

  5. python交互模式切换_Python 交互式窗口 (REPL) - Visual Studio | Microsoft Docs

    使用 Python 交互窗口Work with the Python Interactive window 02/11/2019 本文内容 Visual Studio 为每个 Python 环境提供交 ...

  6. python交互模式设置及VIM的tab补齐

    一.python交互模式设置 Python 解释器具有简单的行编辑功能. 在 Unix 系统上,任何 Python 解释器都可能已经添加了 GNU readline 库支持,这样就具备了精巧的交互编辑 ...

  7. Redis数据操作和与Python交互

    Redis数据操作和与Python交互 文章目录 Redis数据操作和与Python交互 一.数据结构 1.String 字符串类型 2.Hash (哈希) 3.列表 4.Set 集合 5.zset ...

  8. MongoDB与python 交互

    一.安装pymongo 注意 :当同时安装了python2和python3,为区分两者的pip,分别取名为pip2和pip3. 推荐:https://www.cnblogs.com/thunderLL ...

  9. 三、mongodb数据库系列——mongodb和python交互 总结

    一.mongodb和python交互 学习目标 掌握 mongdb和python交互的增删改查的方法 掌握 权限认证的方式使用pymongo模块 1. mongdb和python交互的模块 pymon ...

最新文章

  1. 死锁产生的原因和解锁的方法
  2. python 列表转字典
  3. 移动端Rem之讲解总结
  4. 信息学奥赛一本通(1101:不定方程求解)
  5. Nvelocity 第二章 注释语法
  6. Java集成openCV实现图片背景切换
  7. oracle asm文件查找,Oracle ASM 文件管理
  8. c# word 在当前光标位置插入内容
  9. 如何检查你的MAC是不是原封正品
  10. 【ETH链游】阿蟹Axie Infinity模拟器运行及多开
  11. QUB的中文帮助文档
  12. 黑马程序员pink老师前端入门教程,零基础必看的h5(html5)+css3+移动端前端视频教程(HTML)
  13. 看雪CTF2020 KCTF 秋季赛 签到题
  14. 【JVM】GC垃圾回收(三)——零落成泥碾作尘,只有香如故
  15. Shotcut软件中如何剪辑视频文件(截取其中一段)
  16. python项目开发实战第2版pdf_《树莓派开发实战++第2版》.pdf
  17. 程序员Mac开发软件工具推荐
  18. matlab定义多维数组长度,matlab如何定义三维数组
  19. Xiaojie雷达之路---雷达原理(二刷)天线波束扫描方法
  20. 苹果在线签名服务器搭建,苹果超级签名系统搭建

热门文章

  1. 无心剑中译阿齐姆·普雷姆吉《苦干加巧干》
  2. 【cogs2711】jump,二分答案+倍增套ST表
  3. wordpress主题是php开发的吗,写给想学习wordpress主题开发的朋友们
  4. arch linux 安装xfce_华为荣耀Magicbook安装Manjaro系统指北
  5. notepad++是什么软件_对比国外更优秀的五款国产软件,却不被国人所熟悉
  6. 2017.9.5 能量采集 思考记录
  7. redis的zset的底层实现_Redis底层数据结构之 zset
  8. python朴素贝叶斯分布对数据的要求_统计学习方法与Python实现(三)——朴素贝叶斯法...
  9. rssi室内定位算法原理_室内定位方案常用的4种定位算法
  10. 半透明渲染新技术摘录