MySQL 存储引擎、锁、调优、失误与事务回滚、与python交互、orm
1、存储引擎(处理表的处理器)
1、基本操作
1、查看所有存储引擎
mysql> show engines;
2、查看已有表的存储引擎
mysql> show create table 表名;
3、创建表指定存储引擎
create table 表名(...)engine=myisam;
4、已有表修改存储引擎
alter table 表名 engine=innodb;
2、锁
1、目的 :解决客户端并发访问的冲突问题
2、锁分类
1、锁类型
1、读锁(共享锁)
select :加读锁之后别人不能更改表记录,但可以进行查询
2、写锁(互斥锁、排他锁)
insert、delete、update
加写锁之后别人不能查、不能改
2、锁粒度
1、表级锁 :myisam
2、行级锁 :innodb
3、常用存储引擎特点
1、InnoDB特点
1、共享表空间
表名.frm :表结构和索引文件
表名.ibd :表记录
2、支持行级锁
3、支持外键、事务操作
2、MyISAM特点
1、独享表空间
表名.frm :表结构
表名.myd :表记录 mydata
表名.myi :索引文件 myindex
2、支持表级锁
4、如何决定使用哪个存储引擎
1、执行查操作多的表用 MyISAM(使用InnoDB浪费资源)
2、执行写操作多的表用 InnoDB
3、MySQL调优
1、选择合适的存储引擎
1、读操作多 :MyISAM
2、写操作多 :InnoDB
2、创建索引
在 select、where、order by常涉及到的字段建立索引
3、SQL语句的优化
1、where子句中不使用 != ,否则放弃索引全表扫描
2、尽量避免 NULL 值判断,否则放弃索引全表扫描
优化前 :
select number from t1 where number is null;
优化后 :
在number列上设置默认值0,确保number列无NULL值
select number from t1 where number=0;
3、尽量避免 or 连接条件,否则放弃索引全表扫描
优化前 :
select id from t1 where id=10 or id=20 or id=30;
优化后:
select id from t1 where id=10
union all
select id from t1 where id=20
union all
select id from t1 where id=30;
4、模糊查询尽量避免使用前置 % ,否则全表扫描
select name from t1 where name like "%c%";
5、尽量避免使用 in 和 not in,否则全表扫描
select id from t1 where id in(1,2,3,4);
select id from t1 where id between 1 and 4;
6、尽量避免使用 select * ...;用具体字段代替 * ,不要返回用不到的任何字段
'''SQL语句参数化'''
'''SQL语句参数化''' import pymysql # 1.创建数据库连接对象
db = pymysql.connect(host="localhost",user="root",
password="",database="db4",
charset="utf8")
# 2.创建游标对象
cur = db.cursor() s_id = input("请输入省编号:")
name = input("请输入省名称:") try:
sql_insert = "insert into sheng(s_id,s_name) \
values(%s,%s);"
cur.execute(sql_insert,[s_id,name])# 列表传参
print("ok")
db.commit()
except Exception as e:
db.rollback()
print("Failed",e) cur.close()
db.close()
4、事务和事务回滚
1、定义 :一件事从开始发生到结束的整个过程
2、作用 :确保数据一致性
3、事务和事务回滚应用
1、MySQL中sql命令会自动commit到数据库
show variables like "autocommit";
2、事务应用
1、开启事务
mysql> begin;
mysql> ...一条或多条SQL语句
## 此时autocommit被禁用
2、终止事务
mysql> commit; | rollback;
3、案例
1、背景
你 :建行卡
你朋友 :工商卡
你在建行自动取款机给你朋友的工商卡转账5000元
2、建表
表1、CCB
create table CCB(
name varchar(15),
money decimal(20,2)
);
insert into CCB values("只手遮天",10000);
表2、ICBC
create table ICBC(
name varchar(15),
money decimal(20,2)
);
insert into ICBC values("为所欲为",1000);
3、开始转账
mysql> begin;
mysql> update CCB set money=money-5000 where name="只手遮天";
mysql> update ICBC set money=money+5000 where name="为所欲为";
mysql> commit;
#### 转账成功 ####
import pymysql # 1.创建数据库连接对象
db = pymysql.connect(host="localhost",user="root",
password="",database="db4",
charset="utf8")
# 2.创建游标对象
cur = db.cursor()
# 3.执行SQL语句
# 在sheng表中插入1条记录,云南省
try:
sql_insert = "insert into sheng values\
(19,300002,'西藏');"
cur.execute(sql_insert)
# 把云南省的 id 号改为 666
sql_update = "update sheng set id=666 where id=17;"
cur.execute(sql_update)
# 把台湾省在 sheng 表中删除
sql_delete = "delete from sheng where s_name='台湾省';"
cur.execute(sql_delete)
print("ok")
db.commit()
except Exception as e:
db.rollback()
print("出现错误,已回滚",e) # 5.关闭游标对象
cur.close()
# 6.断开数据库连接
db.close()
5、与python交互
1、交互类型
1、python3
模块名 :pymysql
安装:
在线 :sudo pip3 install pymysql
离线 :pymysql-0.7.11.tar.gz
$ tar -zxvf pymyql-0.7.11.tar.gz
$ cd pymysql-0.7.11
$ sudo python3 setup.py install
2、python2
模块名 :MySQLdb
安装 :sudo pip install mysql-python
2、pymysql使用流程
1、建立数据库连接(db = pymysql.connect(...))
2、创建游标对象(c = db.cursor())
3、游标方法: c.execute("insert ....")
4、提交到数据库 : db.commit()
5、关闭游标对象 :c.close()
6、断开数据库连接 :db.close()
3、connect对象
1、db = pymysql.connect(参数列表)
1、host :主机地址,本地 localhost
2、port :端口号,默认3306
3、user :用户名
4、password :密码
5、database :库
6、charset :编码方式,推荐使用 utf8
2、数据库连接对象(db)的方法
1、db.close() 关闭连接
2、db.commit() 提交到数据库执行
3、db.rollback() 回滚
4、cur = db.cursor() 返回游标对象,用于执行具体SQL命令
3、游标对象(cur)的方法
1、cur.execute(sql命令,[列表]) 执行SQL命令
2、cur.close() 关闭游标对象
3、cur.fetchone() 获取查询结果集的第一条数据
(1,100001,"河北省")
4、cur.fetchmany(n) 获取n条
((记录1),(记录2))
5、cur.fetchall() 获取所有记录
错误:
1、root@"localhost" denied,Using password:YES
2、"localhostt"
3、connect object has no attribute "rollbake"
4、pymysql has no attribute "connect"
import pymysql # 1.创建与数据库连接对象
db = pymysql.connect(host="localhost",user="root",
password="",database="db4",
charset="utf8")
# 2.利用db方法创建游标对象
cur = db.cursor() # 3.利用游标对象的execute()方法执行SQL命令
cur.execute("insert into sheng values\
(16,300000,'台湾省');") # 4.提交到数据库执行
db.commit()
print("ok")
# 5.关闭游标对象
cur.close()
# 6.断开数据库连接
db.close()
6、orm(Object Relation Mapping 对象关系映射)
1、定义
把对象模型映射到MySQL数据库中
2、sqlalchemy安装:
在线 :sudo pip3 install sqlalchemy
离线 :
$ tar -zxvf SQLAlchemy-1.2.10.tar.gz
$ cd SQLAlchemy-1.2.10
$ sudo python3 setup.py install
验证:
$ python3
>>> import sqlalchemy
>>>
3、示例
class User(Base):
__tablename__ = "t1" #声明要创建的表名
id = Column(Integer,primary_key=True)
name = Column(String(20))
解释:
一个类User --> 一张表 t1
表中有两个字段 :id 和 name
select = "select password from user where\
username=%s;" print(select)
from mysqlpython import Mysqlpython # 创建数据库连接对象
sqlh = Mysqlpython("db4") # sql_update = "update sheng set s_name='辽宁省' \
# where s_name='云南省';"
# sqlh.zhixing(sql_update) sql_select = "select * from sheng where id=%s;"
data = sqlh.all(sql_select,[1])
print(data)
实例一:创建一张表
# 连接数据库的模块
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column,Integer,String engine = create_engine("mysql+pymysql://root:123456@localhost/db4",encoding="utf8")
Base = declarative_base() # orm基类 class User(Base): # 继承Base基类
__tablename__ = "t123"
id = Column(Integer,primary_key=True)
name = Column(String(20))
address = Column(String(40)) Base.metadata.create_all(engine)
from mysqlpython import Mysqlpython
from hashlib import sha1 uname = input("请输入用户名:")
pwd = input("请输入密码:")
# 用sha1给pwd加密 s1 = sha1() # 创建sha1加密对象
s1.update(pwd.encode("utf8")) # 指定编码
pwd2 = s1.hexdigest() # 返回16进制加密结果 sqlh = Mysqlpython("db4")
select = "select password from user where \
username=%s;"
result = sqlh.all(select,[uname])
# print(result)
# (('7c4a8d09ca3762af61e59520943dc26494f8941b',),) if len(result) == 0:
print("用户名不存在")
elif result[0][0] == pwd2:
print("登录成功")
else:
print("密码错误")
加密
from pymysql import * class Mysqlpython:
def __init__(self,database,
host="localhost",
user="root",
password="",
port=3306,
charset="utf8"):
self.host = host
self.user =user
self.password = password
self.port = port
self.charset = charset
self.database = database def open(self):
self.db = connect(host=self.host,
user=self.user,
port=self.port,
database=self.database,
password=self.password,
charset=self.charset)
self.cur = self.db.cursor() def close(self):
self.cur.close()
self.db.close() def zhixing(self,sql,L=[]): # pymysql.execute(sql)
try:
self.open()
self.cur.execute(sql,L)
self.db.commit()
print("ok")
except Exception as e:
self.db.rollback()
print("Failed",e)
self.close() def all(self,sql,L=[]):
try:
self.open()
self.cur.execute(sql,L)
result = self.cur.fetchall()
return result
except Exception as e:
print("Failed",e)
self.close()
import pymysql # 1.创建数据库连接对象
db = pymysql.connect(host="localhost",user="root",
password="",database="db4",
charset="utf8")
# 2.创建游标对象
cur = db.cursor() try:
sql_select = "select * from sheng;"
cur.execute(sql_select) data1 = cur.fetchone()
print(data1)
print("*******************") data2 = cur.fetchmany(3)
for m in data2:
print(m)
print("*******************") data3 = cur.fetchall()
for m in data3:
print(m)
print("*******************") db.commit()
except Exception as e:
print(e) cur.close()
db.close()
MySQL 存储引擎、锁、调优、失误与事务回滚、与python交互、orm的更多相关文章
- MySQL性能调优与架构设计——第3章 MySQL存储引擎简介
第3章 MySQL存储引擎简介 3.1 MySQL 存储引擎概述 MyISAM存储引擎是MySQL默认的存储引擎,也是目前MySQL使用最为广泛的存储引擎之一.他的前身就是我们在MySQL发展历程中所 ...
- Mysql存储引擎以及锁机制
一.常用命令 1.查看引擎(默认为InnoDB) 查看mysql提供的存储引擎:show engienes 查看mysql当前默认的存储引擎:show variables like '%storage ...
- mysql innodb存储引擎 锁 事务
以下内容翻译自mysql5.6官方手册. InnoDB是一种通用存储引擎,可平衡高可靠性和高性能.在MySQL 5.6中,InnoDB是默认的MySQL存储引擎.除非已经配置了不同的默认存储引擎, ...
- 第 3 章 MySQL 存储引擎简介
第 3 章 MySQL 存储引擎简介 前言 3.1 MySQL 存储引擎概述 MyISAM 存储引擎是 MySQL 默认的存储引擎,也是目前 MySQL 使用最为广泛的存储引擎之一.他的前身就是我们在 ...
- Mysql存储引擎概念特点介绍及不同业务场景选用依据
目录 MySQL引擎概述 1 MySAM引擎介绍 2 什么是InnoDB引擎? 3 生产环境中如何批量更改MySQL引擎 4 有关MySQL引擎常见企业面试题 MySQL引擎概述 Mysql表存储结构 ...
- MySQL存储引擎差异化实验
本篇把MySQL最常用的存储引擎给大家做一个介绍,然后通过插入.修改和并发实验来了解和验证一下它们之间的一些差异. 一.MySQL存储引擎简介 存储引擎在MySQL结构里占据核心的位置,是上层抽象接口 ...
- MySQL存储引擎简单介绍
MySQL使用的是插件式存储引擎. 主要包含存储引擎有:MyISAM,Innodb,NDB Cluster,Maria.Falcon,Memory,Archive.Merge.Federated. 当 ...
- mysql存储引擎之myisam学习
myisam存储引擎特点:1.不支持事务2.表级锁定(更新时锁整个表,其索引机制是表级索引,这虽然可以让锁定的实现成本很小,但是也同时大大降低 了其并发性能) 3.读写互相阻塞:不仅会在写入的时候阻塞 ...
- mysql 存储引擎介绍
一 存储引擎解释 首先确定一点,存储引擎的概念是MySQL里面才有的,不是所有的关系型数据库都有存储引擎这个概念,后面我们还会说,但是现在要确定这一点. 在讲清楚什么是存储引擎之前,我们先来个比喻, ...
随机推荐
- NAT&Port Forwarding&Port Triggering
NAT Nat,网络地址转换协议.主要功能是实现局域网内的本地主机与外网通信. 在连接外网时,内部Ip地址需要转换为网关(一般为路由器Ip地址)(端口号也需要相应的转换) 如: ...
- New Concept English three(21)
27W 59 Boxing matches were very popular in England two hundred years ago. In those days, boxers foug ...
- zookeeper的c API 单线程与多线程问题 cli_st和cli_mt
同样的程序,在centos和ubuntu上都没有问题,在solaris上问题却多多,据说是solaris管理更加严格. zookeeper_init方法,在传入一个错误的host也能初始化出一个非空的 ...
- 使用jQuery操作DOM(2)
1.获取设置属性值 attr({属性名1:属性值1,属性名2:属性值2}); //设置属性值 removeAttr(“属性名”); //删除属性 注意:如果元素没有此属性,会不起作用 2.获取同辈元素 ...
- 创建Azure Function
azure function的用途在于运行一些逻辑简单的执行逻辑,比如batch job,定时任务,webhook等等.1. 创建azure function创建完毕后,进入app service,选 ...
- java 导入Excel -- 套路及代码分析
一.思路分析 1.我们要做导入,实际上也就是先文件上传,然后读取文件的数据. 2.我们要有一个导入的模板,因为我们导入的Excel列要和我们的数据字段匹配上,所以我们要给它来一个规定,也就是模板. 3 ...
- rancher下的kubernetes之一:构建标准化vmware镜像
学习kubernetes的时候,我们需要在kubernetes环境下实战操作,然而kubernetes环境安装并不容易,现在通过rancher可以简化安装过程,咱们来实战rancher下的kubern ...
- 基于 od 窗口的anti
虽然 odadvance 这类的插件 , 使用驱动将 od 的窗口 进行 隐藏,使用enumwindow ,无法枚举到od的窗口, 但是依然可以 使用r3 的方法 , 对od 窗口检测 之后可以使用 ...
- 关于C++一些面试题目的总结
众所周知,在找工作时笔试题目往往对C++有大量考察,现在我们总结一些C++中比较重要而且可能会考到的知识. 1.判断一下A,B,C,D四个表达式是否正确. int a = 4: A:a += (a + ...
- Codeforces 1012C Hills【DP】*
Codeforces 1012C Hills Welcome to Innopolis city. Throughout the whole year, Innopolis citizens suff ...