名词解释:
事务:一个事务(transaction)中的所有操作,要么全部完成,要么全部不完成,不会结束在中间某个环节。事务在执行过程中发生错误,会被回滚(Rollback)到事务开始前的状态,就像这个事务从来没有执行过一样。简称:原子性
1.进入mysql命令: /usr/local/mysql/bin/mysql -u root -p
2.输入你的密码:xxxx
3. 连接远程服务器 mysql -h 39.106.41.11 -utest -pgloryroad -p3306
mysql 命令需要增加到path路径下
4.展示数据库:show databases;
5.切换数据库: use 数据库名称;
6.查看你当前选中的数据库:select database();
7.展示数据库中的表: show tables;
8.创建数据库:create database gloryroad;
9.创建表:create table test(id int,name varchar(20));
10:插入数据:insert into test values(1,"lilaoshi");
11.更新数据:update test set name="cailaoshi" where id = 2;
12.删除数据库:drop database gloryroad; (慎重操作)
13.删除表的数据:delete from test;
14.删除表数据和表结构:drop table test;
15.建一个复杂的表:CREATE TABLE `studentinfo` ( `ID` int(11) NOT NULL AUTO_INCREMENT COMMENT '不为空的自增长的主键ID', `student_id` varchar(20) NOT NULL, `name` varchar(30) NOT NULL, `sex` char(4) DEFAULT NULL, `tel` varchar(13) NOT NULL, `AdmissionDate` timestamp DEFAULT '0000-00-00 00:00:00', `status` tinyint(2) DEFAULT '0', PRIMARY KEY (`ID`), UNIQUE KEY `tel` (`tel`), UNIQUE KEY `student_id` (`student_id`) ) ENGINE=InnoDB AUTO_INCREMENT=101 DEFAULT CHARSET=utf8 COMMENT='学生信息表';
遇到了一个错误:
ERROR 1067 (42000): Invalid default value for 'AdmissionDate'
产生的原因:
是因为sql_mode中的NO_ZEROR_DATE导制的,在strict mode中不允许'0000-00-00'作为合法日期
查看sql_mode:show variables like 'sql_mode';
+---------------+--------------------------------------------------------------------------------------------------------------+| Variable_name | Value |+---------------+--------------------------------------------------------------------------------------------------------------+| sql_mode | ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION |+---------------+--------------------------------------------------------------------------------------------------------------+
解决办法:set sql_mode='ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,ALLOW_INVALID_DATES,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION';
16:创建一个关联的表:
create table grade( ID int auto_increment not null, stuID varchar(20), course varchar(20) not null, score tinyint(4) default 0, primary key (ID), key idx_stuid(stuID), CONSTRAINT FK_ID FOREIGN KEY(stuID) REFERENCES studentInfo(student_id) )engine=innodb character set utf8 comment "学生成绩表";
名词解释-外键:
外键: grade表中插入的stuID字段的数据必须在studentInfo 的student_id中存在,不在,则不让插入。 删除studentInfo中的student_id数据,那么grade中相关 的stuID数据必须先删除,才能成功。
示例:
studentInfo student_id:2007123 #不能直接删除,grade表中 删除2007123,就可以删除 student_id:2007123 grade: stuID:2007124 插入失败 stuID:2007123 插入成功--》把删掉
*************************************************华丽的分割线***************************************************
python操作数据库的模式:
写一堆参数连接数据
获取游标
执行sql
关闭游标
关闭连接
import pymysql
try:
conn = pymysql.connect( host = "127.0.0.1", port = 3306, user = "root", passwd = "890612wz" ) cur = conn.cursor() cur.execute('CREATE DATABASE IF NOT EXISTS pythonDBnew DEFAULT CHARSET utf8 COLLATE utf8_general_ci;') cur.close() conn.close() print("创建数据库pythonDB成功! ")except pymysql.Error as e: print("Mysql Error %d: %s" % (e.args[0], e.args[1]))建表:
import pymysql
try:
conn = pymysql.connect( host="127.0.0.1", port=3306, user="root", passwd="gloryroad" ) conn.select_db('pythondbnew') # 选择pythonDB数据库 cur = conn.cursor() # 获取游标 # 如果所建表已存在,删除重建 cur.execute("drop table if exists User;") # 执行建表sql语句 cur.execute('''CREATE TABLE `User`( `id` int(11) DEFAULT NULL, `name` varchar(255) DEFAULT NULL, `password` varchar(255) DEFAULT NULL, `birthday` date DEFAULT NULL )ENGINE=innodb DEFAULT CHARSET=utf8;''') cur.close() conn.close() print(u"创建数据表成功")except pymysql.Error as e: print("Mysql Error %d: %s" % (e.args[0], e.args[1]))插入数据:
#coding=utf-8 import pymysql conn = pymysql.connect( host = "127.0.0.1", port = 3306, user = "root", passwd = "gloryroad" , db = "pythondbnew", charset = "utf8" ) # 使用cursor()方法获取数据库的操作游标 cursor = conn.cursor() # 插入一条数据 insert = cursor.execute("insert into user values(1,'Tom','123','1990-01-01')") print(u"添加语句受影响的行数:", insert) # 另一种插入数据方法,通过格式字符串传入值,此方式可以防止sql注入 sql = "insert into user values(%s, %s, %s, %s)" insert = cursor.execute(sql, (3,'lucy','efg','1993-02-01')) print(u"添加语句受影响的行数:", insert) # 关闭游标 cursor.close() # 提交事务 conn.commit() # 关闭数据库连接 conn.close() print(u"sql语句执行成功!")
*************************************************华丽的分割线***************************************************
执行顺序 from where group by having select order by 筛选行-分组-筛选分组结果-排序
*************************************************华丽的分割线***************************************************
数据库常用函数:
分组:select age,avg(age) from student group by age;
select age,count(age) from student group by age having count(*) >1;
select age,count(age) from student where id >3 group by age having count( *) >=1; # where id >3 查询条件下再进行分组
排序:order by
升序: select * from student order by age asc;
降序:select * from student order by age desc;
子查询:单表子查询:select * from student where age in (select age from student where age>28);
两表联合子查询:select name from student where id in (select stu_id from grade where grade<=20);
联合:(使用Union,则所有返回的行都是唯一的,如同您已经对整个结果集合使用了DISTINCT,使用Union ALL则不排重,返回所有的行)
select id from student where id>3 union select id from grade where grade<=40;
select id from student where id>3 union all select id from grade where grade<=40;
内链接:性能比较差,产生了全表扫描
select s.name ,g.course_name ,g.grade from student s,grade g where s.id = g.stu_id;
select s.name ,g.course_name ,g.grade from student s inner join grade g where s.id = g.stu_id;
select s.name ,g.course_name ,g.grade from student s inner join grade g on s.id = g.stu_id;
左连接:
select s.name ,g.course_name ,g.grade from student s left join grade g on s.id = g.stu_id;
右连接:
select s.name ,g.course_name ,g.grade from student s right join grade g on s.id = g.stu_id;
# 注:左右连接,连表查询均可以使用where条件
limit:
select * from student limit 1,1; # 从第一行都展示一条
建立索引:
ALTER TABLE `student` ADD INDEX stu_id_index ( `name` );
查看sql的运行效率:
explain select s.name ,g.course_name ,g.grade from student s,grade g wher e s.id =g.stu_id \G;
如何检查数据库性能:
开启慢查询,将慢查询的sql写入日志,在用explain进行分析
*************************************************华丽的分割线***************************************************
数据库数据写入的四种方式:
1.excel导入
2.程序写入
3.存储过程
4.压测写入数据LR/jmeter