赞
踩
附上一份完整安装教程MySQL的安装与配置
显示所有数据库
show databases;
创建新的数据库
create database; 数据库名
使用数据库
use 数据库名;
创建表
create table 表名
(
数据类型 (长度) 可以跟的属性,
以下同上
)
查看表内所有内容
select * from 表名;
数值
字符串
时间/日期
null
Unsigned
zerofill
自增
非空
默认
MyISAM | InnoDB | |
---|---|---|
事务支持 | 不支持 | 支持 |
数据行锁定 | 不支持 | 支持 |
外键约束 | 不支持 | 支持 |
全文索引 | 支持 | 不支持 |
表空间的大小 | 较小 | 较大,约为二倍 |
常规使用操作:
在物理空间存在 的位置
所有数据库文件都存在Data目录下
本质上还是文件的存储 一个文件夹就对应一个数据库
Mysql 引擎在物理文件上的区别
设置数据库表的字符集编码
CHARSET=UTF8
不设置的话,会是mysql默认的字符集编码 (不支持中文)
Mysql的默认编码是Latin1,不支持中文
在my.ini种配置默认的编码
character-set-server=utf8
alter table 旧表名 rename as 新表名
alter table 表名 add 字段名 列属性
alter table 表名 modify 字段名 列属性[]
例: alter table student modify age varchar(20)
alter table 表名 change 字段名 重置字段名 列属性[]
例: alter table student change age newage int(1)
alter table 表名 drop 字段名
drop table if exist 表名
drop table if exist teacher
注意点 :
- `` 字段名,使用这个包裹
- 注释 -- /**/
- sql 关键字大小写不敏感
- 所有的符号用英文
外键:
方式一、在创建表的时候,增加约束 (麻烦 毕竟复杂)
create table if not exists `grade`( `gradeid` int(10) not null auto_increment comment '年级id', `gradeName` varchar(30) not null comment '年级名称', PRIMARY KEY (`gradeid`) )ENGINE=INNODB DEFAULT CHARSET=UTF8; create table if not exists `student`( `id` int(10) not null auto_increment comment '学号', `name` varchar(30) not null default '无' comment '姓名', `passwd` varchar(60) not null default '123456' comment '密码', `sex` varchar(2) default null comment '性别', `birthday` datetime default null comment '生日', `gradeid` int(10) not null comment '年级', `address` varchar(100) default NULL comment '邮箱', PRIMARY KEY (`id`), KEY `FK_gradeid` (`gradeid`), CONSTRAINT `FK_gradeid` FOREIGN KEY (`gradeid`) REFERENCES `grade`(`gradeid`) )ENGINE=INNODB DEFAULT CHARSET=UTF8;
删除有外键关系的表时 先删除引用别人的表 (从表), 再删除被引用的表 (主表)
方式二、创建表成功后 添加外键约束
create table if not exists `student`( `id` int(10) not null auto_increment comment '学号', `name` varchar(30) not null default '无' comment '姓名', `passwd` varchar(60) not null default '123456' comment '密码', `sex` varchar(2) default null comment '性别', `birthday` datetime default null comment '生日', `gradeid` int(10) not null comment '年级', `address` varchar(100) default NULL comment '邮箱', PRIMARY KEY (`id`) )ENGINE=INNODB DEFAULT CHARSET=UTF8; -- 创建表的时候没有外键关系 alter table `student` add constraint `FK_gradeid` foreign key (`gradeid`) references `grade`(`gradeid`); -- alter table `表名` add constraint `约束名` foreign key (`作为外键的列`) references `哪个表`(`哪个字段`);
alter table
表名
add constraint约束名
foreign key (作为外键的列
) references哪个表
(哪个字段
);
以上操作都是物理外键,数据库级别的外键,不建议使用 ( 避免数据库过多造成困扰 (了解) )
最佳实践
数据库的意义: 数据存储 / 数据管理
DML语言:数据操作语言
插入语句 (添加)
insert into 表名 ([字段名,字段1,字段2,字段3])values(‘值1’,‘值2’,‘值3’)
insert into `grade`(`gradeName`) values ('大三'); -- 由于主键自增我们可以省略主键 (如果不写表字段 会一一匹配) insert into `grade`(`gradeid`,`gradeName`) values (1,'大三'); -- 一般写插入语句 保证数据和字段一一对应 insert into `grade`(`gradeName`) value ('大一'),('大二') -- 插入多个字段 insert into `grade`(`gradeName`) values ('大一'),('大二'); insert into `student` (`name`,`passwd`,`sex`) values ('李四','12345','男'),('王五','22233','男'); insert into `student`() values (3,'李华','223443','女','2005-05-04',2,'唐山');
语法: insert into 表名([字段名1,字段名2,字段名3])values(‘值1’),(‘值2’),(‘值3’)
注意事项:
update 修改谁 (条件) set原来的值 =新值
-- 修改学员名字 找到id=1的学员修改为张全蛋
update `student` set `name` = '张全蛋' where id=1;
-- 不指定条件 会修改所有表 (公司中修改了的话 可以跑路了)
update `student` set `name` = '张全蛋';
-- 语法
-- update 表名 set colnum_name = value where 条件;
-- 修改多个属性
update `student` set `name` = '香香',`address`='唐山'where id=2;
条件: where 子句 约束条件
操作符会返回 布尔值 (真 | 假)
操作符 | 含义 | 范围 | 结果 |
---|---|---|---|
= | 等于 | 5=6 | false |
<> 或 != | 不等于 | 5!=6 | true |
> | 大于 | 5>6 | false |
< | 小于 | 5<6 | true |
>= | 大于等于 | 5>=6 | false |
<= | 小于等于 | 5<=5 | true |
between … and … | 在某个范围内 | [5,8] | |
and | 与 && | 5>1 and 1>2 | false |
or | 或 || | 5>1 or 1>2 | true |
-- 通过多个体条件定位数据
update `student` set name='软软' where name='张全蛋' and birthday=20050504;
语法: update `表名` set colnum_name=value,[colnum_name=value,......] where [条件]
注意:
update `student` set `birthday` = current_date where id=1;
delete 命令
语法: delete from 表名 where []
-- 删除数据 (避免这样写 会全部删除)
delete from `student`;
-- 删除指定数据
delete from `student` where id=3;
truncate 命令
作用:完全清空一个数据或表,表的结构和索引约束不会变
-- 清空student表
truncate `student`;
delete 和 truncate区别
-- 测试 delete 和 TRUNCATE 区别
create table if not exists `test`(
`id` int(4) not null auto_increment,
`coll` varchar(20) not null ,
primary key (`id`)
)engine=INNODB default charset=utf8;
insert into `test`(`coll`) values('1'),('2'),('3');
delete from `test`; -- 不会影响自增
truncate table `test`; -- 自增会清零
了解:
delete 删除的问题
重启数据库:
select 语法
SELECT [ALL | DISTINCT | DISTINCTROW ] [HIGH_PRIORITY] [STRAIGHT_JOIN] [SQL_SMALL_RESULT] [SQL_BIG_RESULT] [SQL_BUFFER_RESULT] [SQL_CACHE | SQL_NO_CACHE] [SQL_CALC_FOUND_ROWS] select_expr [, select_expr ...] [FROM table_references [PARTITION partition_list] [WHERE where_condition] [GROUP BY {col_name | expr | position} [ASC | DESC], ... [WITH ROLLUP]] [HAVING where_condition] [ORDER BY {col_name | expr | position} [ASC | DESC], ...] [LIMIT {[offset,] row_count | row_count OFFSET offset}] [PROCEDURE procedure_name(argument_list)] [INTO OUTFILE 'file_name' [CHARACTER SET charset_name] export_options | INTO DUMPFILE 'file_name' | INTO var_name [, var_name]] [FOR UPDATE | LOCK IN SHARE MODE]]
select 去重 要查询的字段 from 表
(注意:表和字段可以取别名)
xxx join 要连接的表 on 等值判断
where (具体的值,子查询语句)
group by (通过哪个字段来分组)
having (过滤分组后的信息,条件和where是一样的,位置不同)
order by (通过哪个字段排序) [升序/降序]
limit (startindex,pagezize)
业务层面:
查询:跨表、跨数据库…
(Data Query LANGUAGE:数据查询语言)
查询全部的学生
select * from 表名
查询指定字段
select StudentNo
,StudentName
from student;
别名,给结果起一个名字 as 可以给字段取别名,也可以给表取别名
select StudentNo
as 学号,StudentName
as 学生姓名 from student;
函数 Concat (a,b)
select concat(‘姓名:’,StudentName) as 新名字 from student;
语法:select 字段, … from 表
有的时候,列名字不是那么见名知意,我们就可以取别名
as 字段名 as 别名
表名 as 别名
去重 distinct
作用:去除select查询出来的结果中重复的数据,只显示一条
-- 查询以下哪些同学参加了考试,成绩
select * from `result`; -- 查询全部的考试成绩
-- 查询有哪些同学参加了考试
select `studentno` from result;
-- 发现重复数据,去重
select distinct `studentno` from result; -- 发现重复关键字 去重
数据库的列 (表达式)
**查看系统版本 **
select version();
也可以用来计算
select 100*3-1 as 计算结果; -- 用来计算
select @@auto_increment_increment; -- 查询自增的步长
select `studentno`,`studentresult` +1 as '提分后' from result;
-- 学员考试成绩 +1分查看
数据库中的表达式: 文本值,列,NULL,函数,计算表达式,系统变量…
select 表达式
from 表
作用: 检索数据中__符合条件__的值
搜索的条件由一个或者多个表达式组成!结果为 布尔值
逻辑运算符
运算符 | 语法 | 描述 |
---|---|---|
and && | a and b a&&b | 逻辑与,两个都为真 结果为真 |
or || | a or b a||b | 逻辑或,其中一个为真,则结果为真 |
not ! | not a ! a | 逻辑非,真为假;假为真! |
== 尽量使用英文字母 ==
-- where ===================where============= select `studentno`,`studentresult` from result; -- 查询考试成绩在 95-100分之间 select `studentno`,`studentresult` from result where `studentresult` >= 95 and `studentresult` <=100; -- and && select `studentno`,`studentresult` from result where `studentresult` >= 95 && `studentresult` <=100; -- 模糊查询 (区间) select `studentno`,`studentresult` from result where `studentresult` between 95 and 100; -- 除了1000号同学之外的同学的成绩 select `studentno`,`studentresult` from result where `studentno` != 1000; -- != not select `studentno`,`studentresult` from result where not `studentno` = 1000;
模糊查询: 比较运算符
运算符 | 语法 | 描述 |
---|---|---|
is null | a is null | 如果操作符为null,则结果为真 |
is not null | a is not null | 如果操作符不为 null,则结果为真 |
between | a between b and c | 若a 在b和c之间,则结果为真 |
like | a like b | sql匹配,如果 a匹配b,则结果为真 |
in | a in (a1,a2,a3 …) | 假设 a在a1,或者a2…其中的某一个值中,结果为真 |
-- ============模糊查询============ -- 查询姓刘的同学 select `studentno`,`studentname` from student where `studentname` like '刘%'; -- 查询刘后边只有一个字的同学 select `studentno`,`studentname` from student where `studentname` like '刘_'; -- 查询刘后边只有俩个字的同学 select `studentno`,`studentname` from student where `studentname` like '刘__'; -- 查询名字当中有 雨 字的同学 select `studentno`,`studentname` from student where `studentname` like '%雨%'; -- ========== in (具体的一个或者多个值)============== -- 查询 1001 1002 1003 号学员 select `studentno`,`studentname` from `student` where `studentno` in (1001,1002,1003); -- 查询在北京的学生 select `studentno`,`studentname` from `student` where `address` in ('北京'); -- ==== null not null ==== -- 查询地址为空的学生 select `studentno`,`studentname` from `student` where `address` is null; select `studentno`,`studentname` from `student` where `address`='' or address is null; -- 查询有出生日期的同学 不为空 select `studentno`,`studentname` from `student` where `borndate` is not null; -- 查询没有出生日期的同学 为空 select `studentno`,`studentname` from `student` where `borndate` is null;
小红 like ‘小红XXX’
join 对比
-- =============联表查询 join===================== -- 查询参加了考试的同学 (学号,姓名,科目编号,分数) select * from student; select *from result; /* 思路: 1.分析需求 分析查询的字段来自哪些表 (连接查询) 2.确定使用哪种连接查询 ? 7种方式 确认交叉点 (这两个表哪个数据是相同的) 判断条件:学生表中的 studentno = 成绩表的 studentno */ select s.studentno,studentname,subjectno,studentresult from student as s inner join result as r where s.studentno = r.studentno; -- right join select s.studentno,studentname,subjectno,studentresult from student s right join result r on s.studentno = r.subjectno; select s.studentno,studentname,subjectno,studentresult from student s left join result r on s.studentno = r.subjectno;
操作 | 描述 |
---|---|
inner join | 如果表中至少有一个匹配,就返回行 |
left join | 会从左表中返回所有的值,即使右表中没有匹配 |
right join | 会从右表中返回所有的值,即使左表中没有匹配 |
-- =============联表查询 join===================== -- 查询参加了考试的同学 (学号,姓名,科目编号,分数) select * from student; select *from result; /* 思路: 1.分析需求 分析查询的字段来自哪些表 (连接查询) 2.确定使用哪种连接查询 ? 7种方式 确认交叉点 (这两个表哪个数据是相同的) 判断条件:学生表中的 studentno = 成绩表的 studentno */ -- join (连接的表) on (判断条件) 连接查询 -- where 等值查询 select s.studentno,studentname,subjectno,studentresult from student as s inner join result as r where s.studentno = r.studentno; -- right join select s.studentno,studentname,subjectno,studentresult from student s right join result r on s.studentno = r.subjectno; select s.studentno,studentname,subjectno,studentresult from student s left join result r on s.studentno = r.subjectno; -- 查询缺考的同学 select s.studentno,studentname,subjectno,studentresult from student s left join result r on s.studentno = r.subjectno where studentresult is null; -- 思考题 (查询了参加考试的同学信息:学号,学生姓名,科目名,分数) /* 思路: 1.分析需求 分析查询的字段来自哪些表: student、result、subject (连接查询) 2.确定使用哪种连接查询 ? 7种方式 确认交叉点 (这两个表哪个数据是相同的) 判断条件:学生表中的 studentno = 成绩表的 studentno */ select s.studentno,studentname,subjectname,`studentresult` from student s right join result r on r.studentno = s.studentno inner join `subject` sub on r.subjectno = sub.subjectno; -- 我要查询哪些数据 select ... -- 从哪几个表中查 from 表 xxx join 连接的表 on 交叉条件 -- 假设存在多张表查询,慢慢来 先查询两张表 然后再慢慢增加 -- from a left join b -- from a right join b
自连接
自己的表和自己的表连接,核心:一张表拆为两张一样的表即可
父类
categoryid | categoryName |
---|---|
2 | 信息技术 |
3 | 软件开发 |
5 | 美术设计 |
子类
pid | categoryid | categoryName |
---|---|---|
3 | 4 | 数据库 |
2 | 8 | 办公信息 |
3 | 6 | web开发 |
5 | 7 | ps技术 |
操作:查询父类对应的子类关系
父类 | 子类 |
---|---|
信息技术 | 办公信息 |
软件开发 | 数据库 |
软件开发 | web开发 |
美术设计 | ps技术 |
-- 查询父子信息 : 把一张表看为两张一模一样的表 select a.`categoryName` as '父栏目',b.`categoryName` as '子栏目' from `category` as a,`category` as b where a.categoryid = b.`pid`; 、 -- 查询学员所属的年级 (学号,学生的姓名,年级名称) select studentno,studentName,`gradename` from student s inner join `grade` g on s.`gradeid` = g.`gradeid`; -- 查询科目所属的年级 (科目名称,年级名称) select `subjectname`,`gradename` from `subject` sub inner join `grade` g on sub.gradeid = g.gradeid; -- 查询了参加 数据库结构-1 考试 同学的信息: 学号,学生姓名,科目名 分数 select s.`studentno`,`subjectname`,`subjectname`,`studentresult` from student as s inner join `result` as r on s.studentno = r.studentno inner join `subject` as sub on r.subjectno = sub.subjectno where subjectname = '数据库结构-1';
分页
-- 100万 -- 为什么要分页 -- 缓解数据库压力,给人的体验更好,瀑布流 -- 分页,每页只显示五条数据 -- 语法 limit 起始值,页面的大小 -- 网页应用:当前页,总的页数,页数的大小 select s.`studentno`,`subjectname`,`subjectname`,`studentresult` from student as s inner join `result` as r on s.studentno = r.studentno inner join `subject` as sub on r.subjectno = sub.subjectno where subjectname = '数据库结构-1' order by studentresult desc limit 0,5; -- 第一页 limit 0,5 (1-1)*5 -- 第二页 limit 5,5 (2-1)*5 -- 第三页 limit 10,5 (3-1)*5 -- 第N页 limit 0,5 (N-1)*pageSize, -- [pageSize]:页面大小 -- (N-1)*pageSize pageSize 起始值, n 当前页 -- [ (N-1)*pageSize pageSize 起始值 ] -- [ N:当前页 ] -- [ 数据总数/页面大小 = 总页数 ]
语法: limit(查询起始值,pageSize)
-- 查询 java第一学年 课程成绩排名前十的学生 并且分数要大于80的学生信息 (学号,姓名,课程名称,分数)
select s.`studentno` as '学号',
`studentName` as '姓名',
`subjectname` as '课程名称',
`studentresult` as '分数'
from `student` as s
inner join `result` as r
on s.`studentno` = r.`studentno`
inner join `subject` as sub
on sub.`subjectno` = r.`subjectno`
where subjectname = 'java第一学年' and `studentresult` >=80
order by studentresult desc
limit 0,10;
where (这个值是计算出来的)
本质: 在where语句中嵌套一个子查询语句
where (select * from)
-- =================== where ================ -- 1.查询数据库结构-1 的所有考试结果 (学号,科目编号,成绩)降序排序 -- 方式一 使用连接查询 select `studentno`,r.`subjectno`,`studentresult` from `result` as r inner join `subject` as sub on r.subjectno = sub.subjectno where subjectname = '数据结构-1' order by studentresult desc ; -- 查询所有数据结构-1 的学生学号 select subjectno from `subject` where subjectname = '数据结构-1'; -- 方式二:使用子查询 () 由里及外 select `studentno`,`subjectno`,`studentresult` from `result` where subjectno = ( select subjectno from `subject` where subjectname = '数据结构-1' ) order by studentresult desc ; -- 分数不小于80分的学生的学号和姓名 select `studentno`,`studentname` from student s inner join result r on r.studentno = s.studentno where `studentresult` >=80 -- 在这个基础上 增加一个科目 高等数学-2 select s.`studentno`,`studentname` from student s inner join result r on r.studentno = s.studentno where `studentresult` >=80 and `subjectno` = ( select subjectno from `subject` where subjectname = '高等数学-2' ); -- 查询课程为高等数学-2 且分数不小于 80 的同学的学号和姓名 select s.`studentno`,`studentname` from student s inner join result r on s.studentno = r.studentno inner join `subject` sub on r.studentno = sub.subjectno where subjectname = '高等数学-2' and `studentresult` >=80; -- 再改造 select studentno,studentname from student where studentno in ( select studentno from result where studentresult >=80 and subjectno = ( select subjectno from `subject` where subjectname = '高等数学-2' ) );
-- 根据不同课程的平均分 最高分 最低分 平均分大于80
-- 核心:(根据不同的课程分组)
select subjectname,avg(studentresult) as 平均分,max(studentresult),min(studentresult)
from result as r
inner join `subject` as sub
on r.subjectno = sub.subjectno
group by r.subjectno
having 平均分>80; -- 通过什么字段来分组
-- =============== 常用函数 ============ -- 数学运算 select abs(-3); -- 绝对值 select ceiling(9.4); -- 向上取整 select floor(9.4); -- 向下取整 select rand(); -- 返回0-1之间随机数 select sign(10); -- 判断一个数的符号 0返回0 负数返回-1 正数返回1 -- 字符串函数 select char_length('我是应声虫'); -- 字符串长度 select concat('我','爱','学','java'); -- 拼接字符串 select insert('我爱学习python',5,10,'java'); -- 插入 替换 从某个位置 替换某个长度 select lower('My sql'); -- 大写转小写 select upper('mySql'); -- 小写转大写 select instr('hello word','h'); -- 返回第一次出现的子串的索引 select replace('helloword','word','java'); -- 替换出现指定的字符串 select substring('helloword',6,4); -- 返回指定的子字符串 select reverse('你爱学'); -- 反转 -- 查询姓周的同学,名字改成邹 select replace(studentname,'周','邹') from student where studentname like '周%'; -- 时间和日期函数 select current_date(); -- 获取当前日期 select curdate(); -- 获取当前日期 select now(); -- 获取当前时间 select localtime(); -- 获取本地时间 select sysdate(); -- 获取系统时间 select year(now()); -- 获取当前年 -- 系统 select system_user(); select user(); select version();
函数名称 | 描述 |
---|---|
COUNT() | 计数 |
SUM() | 求和 |
AVG() | 平均值 |
MAX() | 最大 |
MIN() | 最小 |
… | … |
-- ============== 聚合函数 ===================
-- 都能够统计表中的数据
select count(studentname) from student; -- count(字段),会忽略所有的null值
select count(*) from student; -- -- count(*),不会忽略所有的null值
select count(1) from student; -- count(1),会忽略所有的null值
select sum(`studentresult`) as 总和 from result;
select avg(`studentresult`) as 平均分 from result;
select max(`studentresult`) as 最高分 from result;
select min(`studentresult`) as 最低分 from result;
什么是MD5
主要增强算法复杂度和不可逆性
MD5不可逆,具体的值的md5是一样的
MD5破解网站的原理,背后有一个字典,MD5加密后的值,加密前的值
-- ======================测试 MD5 加密 =========================== create table `testmd5`( `id` int(4) not null, `name` varchar(20) not null , `pwd` varchar(50) not null , primary key(`id`) )engine=innodb default charset=utf8 insert into `testmd5` values (1,'张三','123456'),(2,'李四','123456'),(3,'王五','123456'); insert into `testmd5` values (4,'小明',md5('123456')); -- 如何校验 将用户传递进来的密码 进行md5加密 然后比对加密后的值 update testmd5 set pwd=md5(pwd) where id=1; -- 加密id=1的密码 update testmd5 set pwd=md5(pwd); -- 加密全部密码 select * from testmd5 where `name` = '小明' and pwd = md5('123456');
要么都成功,要么都失败
将一组 SQL 放在一个批次中去执行
事务原则: ACID
原则 原子性、一致性、隔离性、持久性 (脏读,幻读…)
原子性 Atomicity:
一致性 Consistency:
隔离性 Isolation:
持久性 Durability:
隔离所导致的一些问题
脏读:
指一个事务读取了另外一个事务未提交的数据。
不可重复读:
在一个事务内读取表中的某一行数据,多次读取结果不同。(不一定是错误,可能是某些场合不对)
虚读(幻读)
是指在一个事务内读到了别的事物插入的数据,导致前后读取不一致。
-- ==================== 事务 ===================== -- mysql 是默认开启事务自动提交的 set autocommit = 0; /* 关闭 */ set autocommit = 1; /* 开启(默认) */ -- 手动处理事务 set autocommit = 0; -- 关闭自动条件 -- 事务开启 start transaction -- 标记一个事务的开始,从这个之后的sql 都在同一事务内 /* insert xx insert xx 二者有一个插入失败就提交失败 */ -- 提交: 持久化 (成功) commit -- 回滚: 回到的原来的样子 (失败) rollback -- 事务结束 set autocommit =1; -- 开启自动提交 -- 了解 savepoint 保存点名 -- 设置一个事务的保存点 rollback to savepoint 保存点名 -- 回滚到保存点 release savepoint 保存点名 -- 撤销保存点
模拟场景
-- ====================== 模拟场景 ====================== -- 转账 create database shop character set utf8 collate utf8_general_ci use shop; create table if not exists `account`( `id` int(6) not null auto_increment, `name` varchar(30) not null , `money` decimal(9,2) not null, primary key (`id`) )engine=innodb default charset =utf8; insert into account(`name`,`money`) values ('A',2000.00), ('B',10000.00); -- 模拟转账:事务 set autocommit =0; -- 关闭自动提交 start transaction -- 开启一个事务 (一组事务) update account set money = money-500 where name='A'; -- A-500 update account set money = money+500 where name='B'; -- B+500 commit ; -- 提交事务 就被持久化了 -- rollback; -- 回滚 set autocommit =1; -- 恢复默认值
MySQL官方对索引的定义为:索引(Index)是帮助MySQL高效获取数据的数据结构。
提取句子主干,就可以得到索引的本质:索引是数据结构。
在一个表中,主键索引只能有一个,唯一索引可以有多个
基础语法
-- 索引的使用 -- 1.在创建表的时候给字段增加索引 -- 2.创建完毕后,增加索引 -- 显示所有的索引信息 show index from student; -- 增加一个索引 (索引名 列名) alter table school.student add fulltext index `studentName`(`studentname`); -- explain 分析sql执行的状况 explain select * from student; -- 常规索引 (非全文索引) explain select * from student where match(studentName) against('刘');
-- 索引的使用 -- 1.在创建表的时候给字段增加索引 -- 2.创建完毕后,增加索引 -- 显示所有的索引信息 show index from student; -- 增加一个索引 (索引名 列名) alter table school.student add fulltext index `studentName`(`studentname`); -- explain 分析sql执行的状况 explain select * from student; -- 常规索引 (非全文索引) explain select * from student where match(studentName) against('刘'); create database if not exists app; use app; create table if not exists `app_user`( `id` bigint(20) unsigned not null auto_increment, `name` varchar(50) default '' comment '用户昵称', `email` varchar(50) not null comment '用户邮箱', `phone` varchar(20) default '' comment '手机号', `gender` tinyint(4) unsigned default '0' comment '性别(0:男,1:女)', `password` varchar(100) not null comment '密码', `age` tinyint(4) default '0' comment '年龄', `create_time` datetime default current_timestamp on update current_timestamp, primary key (`id`) )engine =innodb default charset = utf8mb4 comment ='app用户表'; SET GLOBAL log_bin_trust_function_creators = 1; -- 插入100万条数据 20 s 651 ms delimiter $$ -- 写函数之前 必须要写,标志 create function mock_data() returns int begin declare num int default 1000000; declare i int default 0; while i<num do -- 插入语句 insert into app_user (`name`,`email`,`phone`,`gender`,`password`,`age`) values (concat('用户',i),'1197374748@qq.com',concat('18',floor(rand()*((999999999-100000000)+100000000))),floor(rand()*2),uuid(),floor(rand()*100)); set i = i+1; end while; return i; end; select mock_data(); select * from app_user where `name`= '用户9999'; explain select * from app_user where `name`= '用户9999'; -- id_表名_字段名 -- create index 索引名 on 表(字段) 加了索引后查询 47 ms create index id_app_user_name on app_user(`name`); select * from app_user where `name`= '用户9999'; explain select * from app_user where `name`= '用户9999';
索引在小数据量的时候用处不大,但在大数据的时候区别明显
索引的数据结构
Hash 类型的索引
Btree:Innodb的默认数据结构
SQL yog 可视化管理
SQL命令操作
用户表:mysql.user
本质:读这张表进行增删改查
-- ==================== 用户管理 ================= -- 创建用户 create user identified by '密码'; create user Nasa identified by '20010911'; -- 修改密码 (修改当前用户密码) set password = password ('123456'); -- 修改密码 (修改指定用户密码) set password for Nasa = password ('20010911'); -- 重命名 rename user 原名字 to 新名字; rename user Nasa to nasa; -- 用户授权 all privileges (全部权限) 库,表 -- all privileges 除了给别人授权 其他都能干 grant all privileges on *.* to nasa; -- 查询权限 show grants for nasa; -- 查看指定用户的权限 show grants for root@localhost; -- (root用户的权限) GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, RELOAD, SHUTDOWN, PROCESS, FILE, REFERENCES, INDEX, ALTER, SHOW DATABASES, SUPER, CREATE TEMPORARY TABLES, LOCK TABLES, EXECUTE, REPLICATION SLAVE, REPLICATION CLIENT, CREATE VIEW, SHOW VIEW, CREATE ROUTINE, ALTER ROUTINE, CREATE USER, EVENT, TRIGGER, CREATE TABLESPACE, CREATE ROLE, DROP ROLE ON *.* TO `root`@`localhost` WITH GRANT OPTION -- 撤销权限 revoke 哪些权限,在哪个库撤销,给谁撤销 revoke all privileges on *.* from Nasa; -- 删除用户 drop user Nasa; -- mysql 5.7以后数据库导出不支持直接输入密码 不安全 -- 导入 -- 登录的情况下,切换到指定的数据库 #source 备份文件 #mysql -u 用户名 -p 密码 库名 >备份文件
为什么要备份:
Mysql数据库备份的方式
直接拷贝物理文件
在Sqlyog这种可视化工具中手动导出
使用命令行导出 mysqldump 命令行使用
# mysqldump -h 主机 -u 用户名 -p 密码 数据库 表名 > 物理磁盘位置/文件名
mysqldump -hlocalhost -uroot -p20010911 school student > A:/a.sql
# mysqldump -h 主机 -u 用户名 -p 密码 数据库 表1 表2 表3 > 物理磁盘位置/文件名
当数据库比较复杂的时候,我们就需要设计了
糟糕的数据库设计:
良好的数据库设计:
软件开发中,关于数据库的设计:
设计数据库的步骤:(个人博客网站)
数据库的规约、三大规范
为什么需要数据规范化?
三大范式 (了解 面试可能会问)
1.第一范式(1NF)
原子性:保证每一列不可再分
2.第二范式(2NF)
前提:满足第一范式
每张表只描述一件事情
3.第三范式(3NF)
前提:满足第一范式、满足第二范式
第三范式需要确保数据表中的每一列数据都 和主键直接相关,而不能间接相关
(规范数据库的设计)
规范性和性能的问题
关联查询的表不能超过三张表
我们常用的驱动:声卡、显卡等等
数据库也一样需要驱动
我们的程序也需要通过 数据库驱动和数据库打交道
SUN 公司为简化开发人员的操作,提供了一个 (java操作数据库的)规范,俗称JDBC
这些规范的实现由具体的厂商去做
对于开发人员来说,我们只需要掌握JDBC接口的操作即可!
需要用到的java包
java.sql
javax.sql
还需要导入一个数据库驱动包
mysql-connector-java jar
创建测试数据库
package com.nasa.jdbcpack; import java.sql.*; public class JdbcFirstDemo { public static void main(String[] args) throws ClassNotFoundException,SQLException{ // 1.加载驱动 Class.forName("com.mysql.cj.jdbc.Driver"); //固定写法 //2.用户信息和url String url = "jdbc:mysql://localhost:3306/jdbcstudy?useUnicode=true&characterEncoding=utf8&useSSL=true"; // useUnicode=true&characterEncoding=utf8&useSSL=true" String username = "root"; String password = "20010911"; //3.连接成功 数据库对象 Connection con = DriverManager.getConnection(url,username,password); //4.执行sql的对象 去执行sql 可能存在结果 查看返回结果 Statement statement = con.createStatement(); //6.释放连接 String sql = "select * from users;"; ResultSet res = statement.executeQuery(sql); while (res.next()) { System.out.println("id="+res.getObject("id")); System.out.println("name="+res.getObject("name")); System.out.println("password="+res.getObject("password")); System.out.println("email="+res.getObject("email")); System.out.println("birthday="+res.getObject("birthday")); } //6.释放资源 res.close(); statement.close(); con.close(); } }
步骤总结:
DriverManager
//DriverManager.registerDriver(new com.mysql.cj.jdbc.Driver());
Class.forName("com.mysql.cj.jdbc.Driver"); //固定写法
Connection connection = DriverManager.getConnection(url,username,password);
//connection 代表数据库
//数据库设置自动提交
//事务提交
//事务滚回
URL
String url = "jdbc:mysql://localhost:3306/jdbcstudy?useUnicode=true&characterEncoding=utf8&useSSL=true"; // useUnicode=true&characterEncoding=utf8&useSSL=true"
//mysql 默认端口 3306
//jdbc:mysql://主机地址:端口/数据库名?参数1&参数2&参数3
//oralce 默认端口 1521
//jdbc:oracle:thin:@localhost:1521:sid
Statement执行SQL的对象 prepareStatement 执行SQL的对象
statement.executeQuery(); //查询操作 返回ResultSet
statement.execute(); //执行任何sql
statement.executeUpdate(); //更新 插入 删除 都使用这个 返回一个受影响的行数
ResultSet 查询的结果集:封装了所有的查询结果
获得指定的数据模型
resultSet.getObject(); //在不知道列类型的情况下使用
//如果知道列的类型使用指定的类型
resultSet.getString();
resultSet.getInt();
resultSet.getFloat();
resultSet.getDate();
遍历,指针
resultSet.beforeFirst(); //移动到最前边
resultSet.afterLast(); //移动到最后边
resultSet.next(); //移动到下一个
resultSet.previous(); //移动到前一行
resultSet.absolute(row); //移动到指定行
释放资源
//6.释放资源
resultSet.close();
statement.close();
con.close();
jdbc中的statement对象用于向数据发送sql语句,想完成对数据库的增删改查,只需要通过这个对象向数据库发送增删改查语句即可。
Statement对象的executeUpdata方法,用于向数据库发送 增删改的sql语句,excuteUpdata执行完后, 将会返回一个整数(既增删改语句导致了数据库几行数据发生了变化)
Statement.executeQuery方法用于向数据库发送查询语句,executeQuery方法返回代表查询结果的ResultSet对象
CRUD操作-create
使用executeUpdate(String sql)方法完成数据添加操作,示例操作:
Statement statement = con.createStatement();
String sql1 = "insert into user(...) values(...)";
int num = statement.executeUpdate(sql1);
if (num>0) System.out.println("插入成功");
代码实现
executeUpdata
配置文件
db.properties
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/jdbcstudy?useUnicode=true&characterEncoding=utf8&useSSL=true
username=root
password=123321
工具类
package com.nasa.jdbcpackTwo.utils; import java.io.InputStream; import java.sql.*; import java.util.Properties; public class JdbcUtils { private static String driver =null; private static String url =null; private static String username =null; private static String password =null; static { try { InputStream in = JdbcUtils.class.getClassLoader().getResourceAsStream("db.properties"); Properties properties = new Properties(); properties.load(in); driver = properties.getProperty("driver"); url = properties.getProperty("url"); username = properties.getProperty("username"); password = properties.getProperty("password"); //1.驱动只加载一次 Class.forName(driver); } catch (Exception e) { e.printStackTrace(); } } //获取连接 public static Connection getConnection() throws SQLException { return DriverManager.getConnection(url,username,password); } //释放连接资源 public static void release(Connection conn, Statement st, ResultSet rs){ if(rs != null){ try { rs.close(); } catch (SQLException e) { throw new RuntimeException(e); } } if (st != null){ try { st.close(); } catch (SQLException e) { throw new RuntimeException(e); } } if (conn != null){ try { conn.close(); } catch (SQLException e) { throw new RuntimeException(e); } } } }
增
package com.nasa.jdbcpackTwo; import com.nasa.jdbcpackTwo.utils.JdbcUtils; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class TestInsert { public static void main(String[] args){ Connection conn = null; Statement st = null; ResultSet rs = null; try { conn = JdbcUtils.getConnection(); st = conn.createStatement(); String sql = "insert into users(id, name, password, email, birthday)" + "values (4,' 张全蛋',md5('123'),'1123445@qq.cpm','1999-02-13')"; int i = st.executeUpdate(sql); if(i>0) System.out.println("插入成功"); } catch (SQLException e) { e.printStackTrace(); }finally { JdbcUtils.release(conn,st,rs); } } }
删
package com.nasa.jdbcpackTwo; import com.nasa.jdbcpackTwo.utils.JdbcUtils; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class TestDelete { public static void main(String[] args) { Connection conn = null; Statement sta = null; ResultSet rs = null; try { conn = JdbcUtils.getConnection(); sta = conn.createStatement(); String sql = "delete from users where id=4"; int i = sta.executeUpdate(sql); if(i>0) System.out.println("删除成功"); } catch (SQLException e) { e.printStackTrace(); }finally { JdbcUtils.release(conn,sta,rs); } } }
改
package com.nasa.jdbcpackTwo; import com.nasa.jdbcpackTwo.utils.JdbcUtils; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class TestUpdata { public static void main(String[] args) { Connection conn = null; Statement sta = null; ResultSet rs = null; try { conn = JdbcUtils.getConnection(); sta = conn.createStatement(); String sql = "update users set name='李狗' where id=1"; int i = sta.executeUpdate(sql); if(i>0) System.out.println("更新成功"); } catch (SQLException e) { e.printStackTrace(); }finally { JdbcUtils.release(conn,sta,rs); } } }
查
package com.nasa.jdbcpackTwo; import com.nasa.jdbcpackTwo.utils.JdbcUtils; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class TestSelect { public static void main(String[] args) { Connection conn = null; Statement st = null; ResultSet rs = null; try { conn = JdbcUtils.getConnection(); st = conn.createStatement(); //SQL String sql = "select * from users where id=1"; rs = st.executeQuery(sql); while (rs.next()) { System.out.println(rs.getString("name")); } } catch (SQLException e) { e.printStackTrace(); }finally { JdbcUtils.release(conn,st,rs); } } }
SQL注入问题
sql 存在漏洞,会被攻击导致数据泄露 sql会被拼接
PreparedStatement 可以防止SQL注入,效率更高。
package com.nasa.jdbcpackThree; import com.nasa.jdbcpackTwo.utils.JdbcUtils; import java.sql.*; import java.util.Date; public class TestInsert { public static void main(String[] args) { Connection con = null; PreparedStatement pre = null; ResultSet rs = null; try { con = JdbcUtils.getConnection(); //区别 //使用问号占位符 String sql = "insert into users(id, `name`, `password`, `email`, `birthday`)values (?,?,md5(?),?,?)"; pre = con.prepareStatement(sql); //预编译SQL 先写SQL不执行\ pre.setInt(1,6); //id pre.setString(2,"build"); //name pre.setString(3,"123456"); //password pre.setString(4,"11099188@qq.com"); //email // sql.Date 数据库 //java.sql.Date() // util.Date java new Date().getTime() //获得时间戳 pre.setString(5, String.valueOf(new java.sql.Date(new Date().getTime() ))); //birthday int i = pre.executeUpdate(); if(i>0) System.out.println("插入成功"); } catch (SQLException e) { e.printStackTrace(); }finally { JdbcUtils.release(con,pre,null); } } }
package com.nasa.jdbcpackThree; import com.nasa.jdbcpackTwo.utils.JdbcUtils; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class TestDelete { public static void main(String[] args) { Connection con = null; PreparedStatement pre = null; ResultSet rs = null; try { con = JdbcUtils.getConnection(); String sql = "delete from users where id=?"; pre = con.prepareStatement(sql); pre.setInt(1,1); int i = pre.executeUpdate(); if (i>0)System.out.println("删除成功"); } catch (SQLException e) { e.printStackTrace(); }finally { JdbcUtils.release(con,pre,null); } } }
package com.nasa.jdbcpackThree; import com.nasa.jdbcpackTwo.utils.JdbcUtils; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class TestUpdata { public static void main(String[] args) { Connection con = null; PreparedStatement pre = null; ResultSet rs = null; try { con = JdbcUtils.getConnection(); String sql = "update users set `name`=? where id=?"; pre = con.prepareStatement(sql); pre.setString(1,"张冬辉"); pre.setInt(2,6); int i = pre.executeUpdate(); if (i>0)System.out.println("修改成功"); } catch (SQLException e) { e.printStackTrace(); }finally { JdbcUtils.release(con,pre,null); } } }
package com.nasa.jdbcpackThree; import com.nasa.jdbcpackTwo.utils.JdbcUtils; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class TestSelect { public static void main(String[] args) { Connection con = null; PreparedStatement pre = null; ResultSet rs = null; try { con = JdbcUtils.getConnection(); String sql = "select * from users where id=?"; pre = con.prepareStatement(sql); // pre.setString(1,"name"); pre.setInt(1,2); rs = pre.executeQuery(); if (rs.next()) { System.out.println(rs.getString("name")); } } catch (SQLException e) { e.printStackTrace(); }finally { JdbcUtils.release(con,pre,rs); } } }
package com.nasa.jdbcpackThree; import com.nasa.jdbcpackTwo.utils.JdbcUtils; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class SQL_Injection { public static void main(String[] args) { login(" ' 'or 1=1","123456"); // login("李三","234561"); } //登录业务 public static void login(String username,String password){ Connection con = null; PreparedStatement pre = null; ResultSet rs = null; try { con = JdbcUtils.getConnection(); String sql = "select * from users where `name`=? and `password` = md5(?)"; //prepareStatement 防止SQL注入的本质,把传递进来的参数当作字符 //假设其中存在转义字符,就直接忽略 ‘会被直接转义 pre = con.prepareStatement(sql); pre.setString(1,username); pre.setString(2,password); rs = pre.executeQuery(); //查询完返回一个结果集 if (rs.next()) { System.out.println(rs.getString("name")); System.out.println(rs.getString("password")); } } catch (SQLException e) { e.printStackTrace(); }finally { JdbcUtils.release(con,pre,rs); } } }
需要用IntelliJ IDEA商业版
社区版自行下载插件
使用IntelliJ IDEA连接数据库
其余操作此处略过了
借鉴:
在idea中使用mysql(超详细)_idea mysql-CSDN博客
要么都成功,要么都失败
ACID原则
原子性:要么全部完成,要么都不完成
一致性:总数不变
隔离性:多个进程互不干扰
持久性:一但提交不可逆,持久化到数据库了
隔离性的问题:
脏读:一个事务读取了另一个没有提交的事务
不可重复读:在同一个事务内,重复读取表中的数据,表数据发生了改变
虚读(幻读):在一个事务内,读取到了别人插入的数据,导致前后读出来结果不一致。
代码实现
con.setAutoCommit(false);
package com.nasa.jdbcpackFour; import com.nasa.jdbcpackTwo.utils.JdbcUtils; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; public class TestTransaction { public static void main(String[] args) { Connection con = null; PreparedStatement pre = null; Readable rs = null; try { con = JdbcUtils.getConnection(); con.setAutoCommit(false); //关闭数据库的自动提交 自动会开启事务 String sql = "update account set money = money+1000 where name = 'A'"; pre = con.prepareStatement(sql); pre.executeUpdate(); String sql1 = "update account set money = money-1000 where name = 'B'"; pre = con.prepareStatement(sql1); pre.executeUpdate(); //业务完毕 提交事务 con.commit(); System.out.println("提交成功"); } catch (SQLException e) { try { con.rollback(); } catch (SQLException ex) { ex.getStackTrace(); } e.getStackTrace(); }finally { JdbcUtils.release(con,pre,null); } } }
数据库连接–执行完毕–释放
连接–释放 十分浪费系统资源
池化技术:准备一些预先的资源,过来就连接预先准备好的
假设:
—开门 — 服务—关门
—开门 — 业务员:等待—服务—
常用连接数 10个左右
最小连接数:10
最大连接数 15 业务最高承载上限
排队等待
等待超时:100ms
编写连接池,实现一个接口 DataSource
开源数据源实现 (拿来即用)
DBCP
C3P0
Druid
使用了这些数据库连接池之后,我们在项目开发中就不需要编写连接数据库的代码了。
DBCP
需要用到的 jar包
配置文件 dbcpconfig.properties
#???? driverClassName=com.mysql.cj.jdbc.Driver url=jdbc:mysql://localhost:3306/jdbcstudy?useUnicode=true&characterEncoding=utf8&useSSL=true username=root password=20010911 #<!-- ????? --> initialSize=10 #?????? maxActive=50 #<!-- ?????? --> maxIdle=20 #<!-- ?????? --> minIdle=5 #<!-- ???????????? 6000??/1000??60? --> maxWait=60000 #JDBC?????????????????????????????=property;? #???"user" ? "password" ???????????????????????? connectionProperties=useUnicode=true;characterEncoding=UTF8 #??????????????????auto-commit???? defaultAutoCommit=true #driver default ????????????????read-only???? #???????????setReadOnly?????????????????????????Informix? defaultReadOnly= #driver default ??????????????????TransactionIsolation?? #??????????????javadoc??NONE,READ_UNCOMMITTED, READ_COMMITTED, REPEATABLE_READ, SERIALIZABLE defaultTransactionIsolation=READ_UNCOMMITTED
DBCP配置文件 utils目录下创建
package com.nasa.jdbcpackFive.utils; import com.nasa.jdbcpackFive.utils.JdbcUtils_DBCP; import org.apache.commons.dbcp.BasicDataSource; import org.apache.commons.dbcp.BasicDataSourceFactory; import javax.sql.DataSource; import java.io.InputStream; import java.sql.*; import java.util.Properties; public class JdbcUtils_DBCP { public static DataSource dataSource = null; static { try { InputStream in = JdbcUtils_DBCP.class.getClassLoader().getResourceAsStream("dbcpconfig.properties"); Properties properties = new Properties(); properties.load(in); //创建数据源 工厂模式 -->创建 dataSource = BasicDataSourceFactory.createDataSource(properties); } catch (Exception e) { e.printStackTrace(); } } //获取连接 public static Connection getConnection() throws SQLException { return dataSource.getConnection(); //从数据源中获取连接 } //释放连接资源 public static void release(Connection conn, Statement st, ResultSet rs){ if(rs != null){ try { rs.close(); } catch (SQLException e) { throw new RuntimeException(e); } } if (st != null){ try { st.close(); } catch (SQLException e) { throw new RuntimeException(e); } } if (conn != null){ try { conn.close(); } catch (SQLException e) { throw new RuntimeException(e); } } } }
程序实例
package com.nasa.jdbcpackFive; import com.nasa.jdbcpackFive.utils.JdbcUtils_DBCP; import com.nasa.jdbcpackTwo.utils.JdbcUtils; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Date; public class TestDBCP { public static void main(String[] args) { Connection con = null; PreparedStatement pre = null; ResultSet rs = null; try { con = JdbcUtils_DBCP.getConnection(); //区别 //使用问号占位符 String sql = "insert into users(id, `name`, `password`, `email`, `birthday`)values (?,?,md5(?),?,?)"; pre = con.prepareStatement(sql); //预编译SQL 先写SQL不执行\ pre.setInt(1,7); //id pre.setString(2,"OOO"); //name pre.setString(3,"1234561"); //password pre.setString(4,"1109918811@qq.com"); //email // sql.Date 数据库 //java.sql.Date() // util.Date java new Date().getTime() //获得时间戳 pre.setString(5, String.valueOf(new java.sql.Date(new Date().getTime() ))); //birthday int i = pre.executeUpdate(); if(i>0) System.out.println("插入成功"); } catch (SQLException e) { e.printStackTrace(); }finally { JdbcUtils_DBCP.release(con,pre,null); } } }
C3P0
需要用到的 jar包
配置文件 c3p0-config.xml
<?xml version="1.0" encoding="UTF-8"?> <c3p0-config> <!-- c3p0的缺省(默认)配置 如果在代码中"ComboPooledDataSource ds=new ComboPooledDataSource();"这样写就表示使用的是c3p0的缺省(默认)--> <default-config> <property name="driverClass">com.mysql.cj.jdbc.Driver</property> <property name="jdbcUrl">jdbc:mysql://localhost:3306/jdbcstudy?userUnicode=true&characterEncoding=utf8&useSSL=true&serverTimezone=UTC</property> <property name="user">root</property> <property name="password">20010911</property> <property name="acquireIncrement">5</property> <property name="initialPoolSize">10</property> <property name="minPoolSize">5</property> <property name="maxPoolSize">20</property> </default-config> <!-- c3p0的缺省(默认)配置 如果在代码中"ComboPooledDataSource ds=new ComboPooledDataSource("MySQL");"这样写就表示使用的是name为MySQL的数据源(默认)--> <named-config name="MySQL"> <property name="driverClass">com.mysql.cj.jdbc.Driver</property> <property name="jdbcUrl">jdbc:mysql://localhost:3306/jdbcstudy?userUnicode=true&characterEncoding=utf8&useSSL=true&serverTimezone=UTC</property> <property name="user">root</property> <property name="password">20010911</property> <property name="acquireIncrement">5</property> <property name="initialPoolSize">10</property> <property name="minPoolSize">5</property> <property name="maxPoolSize">20</property> </named-config> </c3p0-config>
工具类 utils包
package com.nasa.jdbcpackFive.utils; import com.mchange.v2.c3p0.ComboPooledDataSource; import org.apache.commons.dbcp.BasicDataSourceFactory; import javax.sql.DataSource; import java.io.InputStream; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Properties; public class JdbcUtils_C3P0 { public static DataSource dataSource = null; static { try { // InputStream in = JdbcUtils_C3P0.class.getClassLoader().getResourceAsStream("c3p0-config.xml"); // Properties properties = new Properties(); // properties.load(in); // //代码配置 // dataSource = new ComboPooledDataSource(); // dataSource.setDriverClass(); // dataSource.setUser(); // dataSource.setPassword(); // dataSource.setJdbcUrl(); // // dataSource.setMaxPoolSize(); // dataSource.setMinPoolSize(); //创建数据源 工厂模式 -->创建 dataSource = new ComboPooledDataSource("MySQL"); //配置文件写法 } catch (Exception e) { e.printStackTrace(); } } //获取连接 public static Connection getConnection() throws SQLException { return dataSource.getConnection(); //从数据源中获取连接 } //释放连接资源 public static void release(Connection conn, Statement st, ResultSet rs){ if(rs != null){ try { rs.close(); } catch (SQLException e) { throw new RuntimeException(e); } } if (st != null){ try { st.close(); } catch (SQLException e) { throw new RuntimeException(e); } } if (conn != null){ try { conn.close(); } catch (SQLException e) { throw new RuntimeException(e); } } } }
实例
package com.nasa.jdbcpackFive; import com.nasa.jdbcpackFive.utils.JdbcUtils_C3P0; import com.nasa.jdbcpackFive.utils.JdbcUtils_DBCP; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Date; public class TestC3P0 { public static void main(String[] args) { Connection con = null; PreparedStatement pre = null; ResultSet rs = null; try { con = JdbcUtils_C3P0.getConnection(); //原来是自己实现的 现在使用的是别人的 //区别 //使用问号占位符 String sql = "insert into users(id, `name`, `password`, `email`, `birthday`)values (?,?,md5(?),?,?)"; pre = con.prepareStatement(sql); //预编译SQL 先写SQL不执行\ pre.setInt(1,10); //id pre.setString(2,"狗天大"); //name pre.setString(3,"12123271"); //password pre.setString(4,"11135618811@qq.com"); //email // sql.Date 数据库 //java.sql.Date() // util.Date java new Date().getTime() //获得时间戳 pre.setString(5, String.valueOf(new java.sql.Date(new Date().getTime() ))); //birthday int i = pre.executeUpdate(); if(i>0) System.out.println("插入成功"); } catch (SQLException e) { e.printStackTrace(); }finally { JdbcUtils_DBCP.release(con,pre,null); } } }
结论
无论使用什么数据源,本质还是一样的,DataSource接口不会变,方法就不会变
后续拓展Druid
— 业务级别Mysql学习
— 运维级别Mysql学习
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。