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的更多相关文章

  1. MySQL性能调优与架构设计——第3章 MySQL存储引擎简介

    第3章 MySQL存储引擎简介 3.1 MySQL 存储引擎概述 MyISAM存储引擎是MySQL默认的存储引擎,也是目前MySQL使用最为广泛的存储引擎之一.他的前身就是我们在MySQL发展历程中所 ...

  2. Mysql存储引擎以及锁机制

    一.常用命令 1.查看引擎(默认为InnoDB) 查看mysql提供的存储引擎:show engienes 查看mysql当前默认的存储引擎:show variables like '%storage ...

  3. mysql innodb存储引擎 锁 事务

    以下内容翻译自mysql5.6官方手册. InnoDB是一种通用存储引擎,可平衡高可靠性和高性能.在MySQL 5.6中,InnoDB是默认的MySQL存储引擎.除非已经配置了不同的默认存​​储引擎, ...

  4. 第 3 章 MySQL 存储引擎简介

    第 3 章 MySQL 存储引擎简介 前言 3.1 MySQL 存储引擎概述 MyISAM 存储引擎是 MySQL 默认的存储引擎,也是目前 MySQL 使用最为广泛的存储引擎之一.他的前身就是我们在 ...

  5. Mysql存储引擎概念特点介绍及不同业务场景选用依据

    目录 MySQL引擎概述 1 MySAM引擎介绍 2 什么是InnoDB引擎? 3 生产环境中如何批量更改MySQL引擎 4 有关MySQL引擎常见企业面试题 MySQL引擎概述 Mysql表存储结构 ...

  6. MySQL存储引擎差异化实验

    本篇把MySQL最常用的存储引擎给大家做一个介绍,然后通过插入.修改和并发实验来了解和验证一下它们之间的一些差异. 一.MySQL存储引擎简介 存储引擎在MySQL结构里占据核心的位置,是上层抽象接口 ...

  7. MySQL存储引擎简单介绍

    MySQL使用的是插件式存储引擎. 主要包含存储引擎有:MyISAM,Innodb,NDB Cluster,Maria.Falcon,Memory,Archive.Merge.Federated. 当 ...

  8. mysql存储引擎之myisam学习

    myisam存储引擎特点:1.不支持事务2.表级锁定(更新时锁整个表,其索引机制是表级索引,这虽然可以让锁定的实现成本很小,但是也同时大大降低 了其并发性能) 3.读写互相阻塞:不仅会在写入的时候阻塞 ...

  9. mysql 存储引擎介绍

    一  存储引擎解释 首先确定一点,存储引擎的概念是MySQL里面才有的,不是所有的关系型数据库都有存储引擎这个概念,后面我们还会说,但是现在要确定这一点. 在讲清楚什么是存储引擎之前,我们先来个比喻, ...

随机推荐

  1. avr 烧录失败

    用Atmel studio 6.0 配置mkII烧录器 使用上位机bat程序烧录 提示错误:firmware is old... 1参考(关于FUSe setting) http://www.cnbl ...

  2. Windbg 调试工具32位/64位版本下载

    最新的Windbg调试工具32位/64位版本越来越不好下载了,这里通过CSDN的渠道给大家一个下载地址,帮助大家更好下载工具: https://github.com/EasyDarwin/Tools/ ...

  3. allow-hotplug eth0 allow-hotplug error

    /********************************************************************* * allow-hotplug eth0 error * ...

  4. Linux服务器运行环境搭建(二)——Redis数据库安装

    官网地址:http://redis.io/ 官网下载地址:http://redis.io/download 1. 下载Redis源码(tar.gz),并上传到Linux 2. 解压缩包:tar zxv ...

  5. 用xapian来做索引

    最近一个项目需要正则搜索MongoDB,400多万的数据一次查询要20s以上,需要建立一个前端索引服务.本着部署简单.开发容易的原则,找到了xapian这个索引库. 我使用的是Python的接口,xa ...

  6. BZOJ1014 JSOI2008 火星人prefix 【非旋转Treap】*

    BZOJ1014 JSOI2008 火星人prefix Description 火星人最近研究了一种操作:求一个字串两个后缀的公共前缀.比方说,有这样一个字符串:madamimadam,我们将这个字符 ...

  7. (2/2) 为了理解 UWP 的启动流程,我从零开始创建了一个 UWP 程序

    每次使用 Visual Studio 的模板创建一个 UWP 程序,我们会在项目中发现大量的项目文件.配置.应用启动流程代码和界面代码.然而这些文件在 UWP 程序中到底是如何工作起来的? 我从零开始 ...

  8. Oracle中Inner join和Where的区别

    1 .Where子句中使用的连接语句,在数据库语言中,被称为隐性连接.Inner join--on子句产生的连接称为显性连接.(其他Join参数也是显性连接)Where 和Inner join产生的连 ...

  9. 从数据库导出数据到excel之List<List<Object>>导出

    说明:有时候数据处理为List<List<Object>>更方便 姊妹篇:从数据库导出数据到excel之List<Map<>>导出 兄弟篇:从数据库导出 ...

  10. 纯 as3 项目中引用 fl 包下的类

    如果安装了 Flash IDE, 将下面的文件添加到项目的 libs 中即可:D:\Program Files\Adobe\Adobe Flash CS6\Common\Configuration\A ...