MySQL SQL语句分类
DDL:数据定义语句[create表,库…]
DML:数据操作语句[增加insert,修改update,删除 delete]
DQL:数据查询语句[select ]
DCL:数据控制语句[管理数据库:比如用户权限grant revoke ]
数据库基本操作
常用数据类型(列类型)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 CREATE TABLE emp( `id` INT , `name` VARCHAR (32 ), `sex` CHAR (1 ), `birthday` DATE , `entry_date` DATETIME, `job` VARCHAR (32 ), `Salary` DOUBLE , `resume` TEXT)CHARACTER SET utf8 COLLATE utf8_bin ENGINE INNODB; INSERT INTO emp VALUES (100 ,'张三' ,'男' ,'2000-12-11' ,'2022-08-03 22:01:20' ,'Java开发' ,'20000' ,'法外狂徒' ); ALTER TABLE emp ADD `image` VARCHAR (32 ) NOT NULL DEFAULT '' AFTER resume; ALTER TABLE emp MODIFY `job` VARCHAR (60 ) NOT NULL DEFAULT '' ; DESC emp ALTER TABLE emp DROP `sex`;RENAME table emp TO employee; ALTER TABLE employee CHARACTER SET utf8;ALTER TABLE employee CHANGE `name` `user_name` VARCHAR (64 ) NOT NULL DEFAULT '' ;DESC employee;
数据库CRUD语句
Insert语句(添加数据)
1 2 3 4 5 6 7 8 9 10 11 12 #说明 insert 语句的细节
Update语句(更新数据)
1 2 3 4 5 6 7 8 9 10 11 12 UPDATE employee SET salary = 50000 ;UPDATE employee SET salary = 30000 WHERE user_name= '张三' ;UPDATE employee SET salary = salary+ 10000 WHERE user_name= '王五' ;SELECT * FROM employee;
Delete语句(删除数据)
1 2 3 4 5 6 7 DELETE FROM employee WHERE user_name = '张三' ;SELECT * FROM employee;
Select语句(查找数据)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 CREATE TABLE student ( id INT NOT NULL DEFAULT 1 , NAME VARCHAR ( 20 ) NOT NULL DEFAULT '' , chinese FLOAT NOT NULL DEFAULT 0.0 , english FLOAT NOT NULL DEFAULT 0.0 , math FLOAT NOT NULL DEFAULT 0.0 ); INSERT INTO student ( id, NAME, chinese, english, math )VALUES ( 1 , '刘备' , 89 , 78 , 90 );INSERT INTO student ( id, NAME, chinese, english, math )VALUES ( 2 , '张飞' , 67 , 98 , 56 );INSERT INTO student ( id, NAME, chinese, english, math )VALUES ( 3 , '宋江' , 87 , 78 , 77 );INSERT INTO student ( id, NAME, chinese, english, math )VALUES ( 4 , '关羽' , 88 , 98 , 90 );INSERT INTO student ( id, NAME, chinese, english, math )VALUES ( 5 , '赵云' , 82 , 84 , 67 );INSERT INTO student ( id, NAME, chinese, english, math )VALUES ( 6 , '欧阳锋' , 55 , 85 , 45 );INSERT INTO student ( id, NAME, chinese, english, math )VALUES ( 7 , '黄蓉' , 75 , 65 , 30 );SELECT * FROM student;SELECT `name`,english FROM student;SELECT DISTINCT english from student;SELECT DISTINCT `name` ,english FROM student;
使用表达式对查询的列进行运算 在 select 语句中可使用 as 语句
1 2 3 4 5 6 SELECT `name` ,(chinese+ english+ math) FROM student;SELECT `name` ,(chinese+ english+ math+ 10 ) FROM student;SELECT `name` ,(chinese+ english+ math+ 10 ) AS total_score FROM student;
在where子句中经常使用的运算符
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 1. 查询姓名为赵云的学生成绩SELECT * FROM student WHERE `name` = '赵云' ;2. 查询英语成绩大于90 分的同学SELECT * FROM student WHERE english > 90 ;3. 查询总分大于200 分的所有同学SELECT * FROM student WHERE (chinese+ english+ math) > 200 ;4. 查询math大于60 并且(and ) id大于4 的学生成绩SELECT * FROM student WHERE math > 60 AND id > 4 ;5. 查询英语成绩大于语文成绩的同学SELECT * FROM student WHERE english > chinese;6. 查询总分大于200 分并且数学成绩大于语文成绩,的姓刘的学生.SELECT * FROM student WHERE (chinese+ english+ math) > 200 AND math > chinese AND `name`LIKE '刘%' ;7. 查询英语分数在80 - 90 之间的同学。SELECT * FROM student WHERE english BETWEEN 80 AND 90 ;8. 查询数学分数为89 ,90 ,91 的同学。SELECT * FROM student WHERE math IN (89 ,90 ,91 );9. 查询数学比语文少30 分的同学。SELECT * FROM student WHERE math+ 30 <= chinese ;
使用order by 子句排序查询结果
1 2 3 4 5 6 7 SELECT * FROM student ORDER BY math;SELECT `name`,(chinese+ english+ math)AS total_score FROM student ORDER BY total_score DESC ;SELECT `name`, (chinese + english + math) AS total_score FROM studentWHERE `name` LIKE '刘%' ORDER BY total_score;
合计/统计函数 1.count
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 SELECT COUNT (* ) FROM student;SELECT count (* ) FROM student WHERE math > 80 ;SELECT count (* ) FROM student WHERE (math+ english+ chinese) > 250 ;CREATE TABLE t15 (`name` VARCHAR (20 )); INSERT INTO t15 VALUES ('tom' );INSERT INTO t15 VALUES ('jack' );INSERT INTO t15 VALUES ('mary' );INSERT INTO t15 VALUES (NULL );SELECT * FROM t15;SELECT COUNT (* ) FROM t15; SELECT COUNT (`name`) FROM t15;
2.sum
1 2 3 4 5 6 7 8 9 10 SELECT SUM (math) FROM student; SELECT SUM (math) AS math_total_score,SUM (english),SUM (chinese) FROM student; SELECT SUM (math + english + chinese) FROM student; SELECT SUM (chinese)/ COUNT (* ) FROM student;SELECT SUM (`name`) FROM student;
3.avg
1 2 3 SELECT AVG (math) FROM student; SELECT AVG (math + english + chinese)FROM student;
4.mxa/min
1 2 3 4 SELECT MAX (math + english + chinese), MIN (math + english + chinese)FROM student; SELECT MAX (math) AS math_high_socre, MIN (math) AS math_low_socre FROM student;
5.使用 group by 子句对列进行分组
6.使用 having 子句对分组后的结果进行过滤
1 2 3 4 5 6 SELECT AVG (sal),MAX (sal),deptno FROM emp GROUP BY deptno;SELECT AVG (sal),MIN (sal),deptno,job FROM emp GROUP BY deptno,job;SELECT AVG (sal)AS avg_sal,deptno FROM emp GROUP BY deptno HAVING avg_sal < 2000 ;
字符串相关函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 SELECT CHARSET(ename) FROM emp; SELECT CONCAT(ename, ' 工作是 ' , job) FROM emp; SELECT INSTR('hanshunping' , 'ping' ) FROM DUAL; SELECT UCASE(ename) FROM emp; SELECT LCASE(ename) FROM emp; SELECT LEFT (ename, 2 ) FROM emp; SELECT LENGTH(ename) FROM emp; SELECT ename, REPLACE(job,'MANAGER' , '经理' ) FROM emp;SELECT STRCMP('hsp' , 'hsp' ) FROM DUAL; SELECT SUBSTRING (ename, 1 , 2 ) FROM emp; SELECT LTRIM(' 学习学习' ) FROM DUAL;SELECT RTRIM('学习学习 ' ) FROM DUAL;SELECT TRIM (' 学习学习 ' ) FROM DUAL; SELECT CONCAT(LCASE(SUBSTRING (ename,1 ,1 )),SUBSTRING (ename,2 ))AS new_name FROM emp;SELECT CONCAT(LCASE(LEFT (ename,1 )), SUBSTRING (ename,2 )) AS new_name FROM emp
数学相关函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 SELECT ABS (-10 ) FROM DUAL; SELECT BIN(10 ) FROM DUAL; SELECT CEILING (-1.1 ) FROM DUAL; SELECT CONV(8 , 10 , 2 ) FROM DUAL; SELECT CONV(16 , 16 , 10 ) FROM DUAL; SELECT FLOOR (-1.1 ) FROM DUAL; SELECT FORMAT(78.125458 ,2 ) FROM DUAL; SELECT LEAST(0 ,1 , -10 , 4 ) FROM DUAL; SELECT MOD (10 , 3 ) FROM DUAL; SELECT RAND() FROM DUAL;
时间日期相关函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 SELECT CURRENT_DATE () FROM DUAL; SELECT CURRENT_TIME () FROM DUAL; SELECT CURRENT_TIMESTAMP () FROM DUALCREATE TABLE mes(id INT , content VARCHAR (30 ), send_time DATETIME ); INSERT INTO mes VALUES (1 , '北京新闻' , CURRENT_TIMESTAMP ());INSERT INTO mes VALUES (2 , '上海新闻' , NOW());INSERT INTO mes VALUES (3 , '广州新闻' , NOW());SELECT * FROM mes;SELECT NOW() FROM DUAL; SELECT id, content, DATE (send_time)FROM mes; SELECT * FROM mes WHERE DATE_ADD(send_time, INTERVAL 10 MINUTE ) >= NOW();SELECT * FROM mes WHERE send_time >= DATE_SUB(NOW(), INTERVAL 10 MINUTE );SELECT DATEDIFF('2011-11-11' , '1990-01-01' ) FROM DUAL; SELECT DATEDIFF(NOW(), '1986-11-11' ) FROM DUAL; SELECT DATEDIFF(DATE_ADD('1986-11-11' , INTERVAL 80 YEAR ), NOW())FROM DUAL;SELECT TIMEDIFF('10:11:11' , '06:10:10' ) FROM DUAL; SELECT YEAR (NOW()) FROM DUAL;SELECT MONTH (NOW()) FROM DUAL;SELECT DAY (NOW()) FROM DUAL;SELECT MONTH ('2013-11-10' ) FROM DUAL; SELECT UNIX_TIMESTAMP() FROM DUAL; SELECT FROM_UNIXTIME(1618483484 , '%Y-%m-%d' ) FROM DUAL;SELECT FROM_UNIXTIME(1618483100 , '%Y-%m-%d %H:%i:%s' ) FROM DUAL;
加密和系统函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 SELECT USER () FROM DUAL; SELECT DATABASE(); SELECT MD5('fzy' ) FROM DUAL;SELECT LENGTH(MD5('fzy' )) FROM DUAL; CREATE TABLE hsp_user(id INT , `name` VARCHAR (32 ) NOT NULL DEFAULT '' , pwd CHAR (32 ) NOT NULL DEFAULT '' ); INSERT INTO hsp_user VALUES (100 , '韩顺平' , MD5('hsp' ));SELECT * FROM hsp_user; SELECT * FROM hsp_user WHERE `name`= '韩顺平' AND pwd = MD5('hsp' )SELECT PASSWORD('hsp' ) FROM DUAL; SELECT * FROM mysql.user;
流程控制函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 # 演示流程控制语句 # IF(expr1,expr2,expr3) 如果 expr1 为 True ,则返回 expr2 否则返回 expr3 SELECT IF(TRUE , '北京' , '上海' ) FROM DUAL;# IFNULL(expr1,expr2) 如果 expr1 不为空 NULL ,则返回 expr1,否则返回 expr2 SELECT IFNULL( NULL , '韩顺平教育' ) FROM DUAL;# SELECT CASE WHEN expr1 THEN expr2 WHEN expr3 THEN expr4 ELSE expr5 END ; [类似多重分支.] # 如果 expr1 为 TRUE ,则返回 expr2,如果 expr2 为 t, 返回 expr4, 否则返回 expr5 SELECT CASE WHEN TRUE THEN 'jack' WHEN FALSE THEN 'tom' ELSE 'mary' END ;SELECT ename, IF(comm IS NULL , 0.0 , comm)FROM emp;SELECT ename, IFNULL(comm, 0.0 )FROM emp; SELECT ename, (SELECT CASE WHEN job = 'CLERK' THEN '职员' WHEN job = 'MANAGER' THEN '经理' WHEN job = 'SALESMAN' THEN '销售人员' ELSE job END ) AS 'job' FROM emp;
增强 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 SELECT * FROM emp WHERE hiredate > '1992-01-01' ;SELECT ename, sal FROM emp WHERE ename LIKE 'S%' SELECT ename, sal FROM emp WHERE ename LIKE '__O%' ;SELECT * FROM emp WHERE mgr IS NULL ; DESC empSELECT * FROM emp ORDER BY sal;SELECT * FROM emp ORDER BY deptno ASC , sal DESC ;
分页查询 基本语法:select … limit start, rows
表示从start+1行开始取,取出rows行, start 从0开始计算
分组函数和分组子句 group by 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 SELECT COUNT (* ), AVG (sal), job FROM emp GROUP BY job; SELECT COUNT (* ), COUNT (comm) FROM emp;SELECT COUNT (* ), COUNT (IF(comm IS NULL , 1 , NULL )) FROM emp;SELECT COUNT (* ), COUNT (* ) - COUNT (comm) FROM emp;SELECT COUNT (DISTINCT mgr) FROM emp; SELECT MAX (sal) - MIN (sal) FROM emp;
顺序 如果select语句同时包含有group by ,having ,limit,order by
那么他们的顺序是group by , having , orderby,limit
1 2 3 4 5 6 SELECT deptno,AVG (sal)as avg_sal FROM emp GROUP BY deptno HAVING avg_sal > 1000 ORDER BY avg_sal DESC LIMIT 0 ,2 ;
多表查询 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 SELECT ename,sal,dname,emp.deptnoFROM emp, deptWHERE emp.deptno = dept.deptno;SELECT * FROM emp;SELECT * FROM dept;SELECT * FROM salgrade; SELECT ename,sal,dname,emp.deptnoFROM emp, deptWHERE emp.deptno = dept.deptno AND emp.deptno = 10 select ename, sal, gradefrom emp , salgradewhere sal between losal and hisal;SELECT ename,sal,dname FROM emp,dept WHERE emp.deptno= dept.deptno ORDER BY emp.deptno DESC ;
自连接 自连接是指在同一张表的连接查询[将同一张表看做两张表]。
1 2 3 4 5 6 7 8 9 10 SELECT worker.ename AS '职员名' , boss.ename AS '上级名' FROM emp worker, emp bossWHERE worker.mgr = boss.empno;
子查询 子查询是指嵌入在其它 sql 语句中的 select 语句,也叫嵌套查询
单行子查询是指只返回一行数据的子查询语句
多行子查询指返回多行数据的子查询 使用关键字 in
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 SELECT deptno FROM emp WHERE ename = 'SMITH' ;SELECT * FROM emp WHERE deptno = ( SELECT deptno FROM emp WHERE ename = 'SMITH' ) SELECT ename,job,sal,deptno FROM emp WHERE job IN ( SELECT DISTINCT job FROM emp WHERE deptno = 10 ) AND deptno != 10 ;
在多行子查询中使用 all ,any操作符
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 SELECT ename, sal, deptno FROM emp WHERE sal > ALL ( SELECT sal FROM emp WHERE deptno = 30 ); SELECT ename, sal, deptno FROM emp WHERE sal > ( SELECT MAX (sal) FROM emp WHERE deptno = 30 ); SELECT ename, sal, deptno FROM emp WHERE sal > any ( SELECT sal FROM emp WHERE deptno = 30 ); SELECT ename, sal, deptno FROM emp WHERE sal > ( SELECT MIN (sal) FROM emp WHERE deptno = 30 );
当临时表使用 1 2 3 4 5 6 7 8 9 10 11 12 select goods_id, ecs_goods.cat_id, goods_name, shop_price from ( SELECT cat_id , MAX (shop_price) as max_price FROM ecs_goods GROUP BY cat_id ) temp , ecs_goods where temp.cat_id = ecs_goods.cat_id and temp.max_price = ecs_goods.shop_price;
多列子查询 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 SELECT * FROM emp WHERE (deptno , job ) = ( SELECT deptno ,job FROM emp WHERE ename = 'ALLEN' ) AND ename <> 'ALLEN' ; SELECT * FROM student WHERE (math,english,chinese)= ( SELECT math,english,chinese FROM student WHERE `name`= '宋江' );
表复制 自我复制数据(蠕虫复制) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 CREATE TABLE my_tab01 ( id INT , `name` VARCHAR (32 ), sal DOUBLE , job VARCHAR (32 ), deptno INT ); DESC my_tab01;SELECT * FROM my_tab01;INSERT INTO my_tab01 (id, `name`, sal, job,deptno) SELECT empno, ename, sal, job, deptno FROM emp; INSERT INTO my_tab01 SELECT * FROM my_tab01;SELECT COUNT (* ) FROM my_tab01;CREATE TABLE my_tab02 LIKE emp; DESC my_tab02;INSERT INTO my_tab02 SELECT * FROM emp;SELECT * FROM my_tab02; create table my_tmp like my_tab02;insert into my_tmp select distinct * from my_tab02;delete from my_tab02; insert into my_tab02 select * from my_tmp; drop table my_tmp;select * from my_tab02;
合并查询 1 2 3 4 5 6 7 8 9 10 11 12 13 14 SELECT ename,sal,job FROM emp WHERE sal> 2500 ; SELECT ename,sal,job FROM emp WHERE job= 'MANAGER' ; SELECT ename,sal,job FROM emp WHERE sal> 2500 UNION ALL SELECT ename,sal,job FROM emp WHERE job= 'MANAGER' ; SELECT ename,sal,job FROM emp WHERE sal> 2500 UNION SELECT ename,sal,job FROM emp WHERE job= 'MANAGER' ;
外连接 1.左外连接(如果左侧的表完全显示我们就说是左外连接)
2.右外连接(如果右侧的表完全显示我们就说是右外连接)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 CREATE TABLE stu (id INT , `name` VARCHAR (32 )); INSERT INTO stu VALUES (1 , 'jack' ),(2 ,'tom' ),(3 , 'kity' ),(4 , 'nono' );SELECT * FROM stu;CREATE TABLE exam(id INT , grade INT ); INSERT INTO exam VALUES (1 , 56 ),(2 ,76 ),(11 , 8 );SELECT * FROM exam;SELECT `name`, stu.id, gradeFROM stu, examWHERE stu.id = exam.id; SELECT `name`, stu.id, grade FROM stu LEFT JOIN exam ON stu.id = exam.id; SELECT `name`, stu.id, grade FROM stu RIGHT JOIN exam ON stu.id = exam.id; SELECT dname,ename,job FROM dept LEFT JOIN emp ON dept.deptno= emp.deptno; SELECT dname,ename,job FROM emp RIGHT JOIN dept ON dept.deptno= emp.deptno;
约束 约束用于确保数据库的数据满足特定的商业规则。在mysql中,约束包括: not null,unique,primary key,foreign key,和check五种.
primary key(主键) 字段名 字段类型 primary key
用于唯一的标示表行的数据,当定义主键约束后,该列不能重复。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 CREATE TABLE t17(id INT PRIMARY KEY, `name` VARCHAR (32 ),email VARCHAR (32 )); INSERT INTO t17VALUES (1 , 'jack' , 'jack@sohu.com' );INSERT INTO t17VALUES (2 , 'tom' , 'tom@sohu.com' );INSERT INTO t17VALUES (1 , 'hsp' , 'hsp@sohu.com' );SELECT * FROM t17; INSERT INTO t17VALUES (NULL , 'hsp' , 'hsp@sohu.com' ); CREATE TABLE t18(id INT PRIMARY KEY, `name` VARCHAR (32 ), PRIMARY KEY email VARCHAR (32 )); CREATE TABLE t18(id INT , `name` VARCHAR (32 ), email VARCHAR (32 ), PRIMARY KEY (id, `name`) ); INSERT INTO t18VALUES (1 , 'tom' , 'tom@sohu.com' );INSERT INTO t18VALUES (1 , 'jack' , 'jack@sohu.com' );INSERT INTO t18VALUES (1 , 'tom' , 'xx@sohu.com' ); SELECT * FROM t18; CREATE TABLE t19(id INT , `name` VARCHAR (32 ) PRIMARY KEY, email VARCHAR (32 ) ); CREATE TABLE t20(id INT , `name` VARCHAR (32 ) , email VARCHAR (32 ), PRIMARY KEY(`name`) ); DESC t20 DESC t18
not null(非空)
unique(唯一)
foreign key(外键)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 CREATE TABLE my_class (id INT PRIMARY KEY , `name` VARCHAR (32 ) NOT NULL DEFAULT '' ); CREATE TABLE my_stu (id INT PRIMARY KEY , `name` VARCHAR (32 ) NOT NULL DEFAULT '' , class_id INT , FOREIGN KEY (class_id) REFERENCES my_class(id));DESC my_stu;INSERT INTO my_classVALUES (100 , 'java' ), (200 , 'web' );INSERT INTO my_classVALUES (300 , 'php' );SELECT * FROM my_class;SELECT * FROM my_class;INSERT INTO my_stuVALUES (1 , 'tom' , 100 );INSERT INTO my_stuVALUES (2 , 'jack' , 200 );INSERT INTO my_stuVALUES (3 , 'hsp' , 300 );INSERT INTO my_stuVALUES (4 , 'mary' , 400 ); INSERT INTO my_stuVALUES (5 , 'king' , NULL ); SELECT * FROM my_class; SELECT * FROM my_stu; DELETE FROM my_classWHERE id = 100 ;
check 用于强制行数据必须满足的条件,假定在sal列上定义了check约束,并要求sal列值在1000-2000之间如果不再1000-2000之间就会提示出错。
1 2 3 4 5 6 CREATE TABLE t23 ( id INT PRIMARY KEY, `name` VARCHAR (32 ) , sex VARCHAR (6 ) CHECK (sex IN ('man' ,'woman' )), sal DOUBLE CHECK ( sal > 1000 AND sal < 2000 ) );
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 CREATE TABLE goods( goods_id INT PRIMARY KEY, goods_name VARCHAR (64 ) NOT NULL DEFAULT '' , unitprice DECIMAL (10 ,2 ) NOT NULL DEFAULT 0 CHECK (unitprice BETWEEN 1.0 AND 9999.99 ), provider VARCHAR (64 ) NOT NULL DEFAULT '' ); CREATE TABLE customer( customer_id VARCHAR (16 ) PRIMARY KEY, `name` VARCHAR (64 ) NOT NULL DEFAULT '' , `address` VARCHAR (64 )NOT NULL DEFAULT '' , `email` VARCHAR (64 ) UNIQUE NOT NULL , `sex` ENUM('男' ,'女' ) NOT NULL , card_Id VARCHAR (18 )); CREATE TABLE purchase( order_id INT UNSIGNED PRIMARY KEY, customer_id VARCHAR (16 )NOT NULL DEFAULT '' , goods_id INT NOT NULL DEFAULT 0 , nums INT NOT NULL DEFAULT 0 , FOREIGN KEY (customer_id) REFERENCES customer(customer_id), FOREIGN KEY (goods_id) REFERENCES goods(goods_id)); DESC goods;DESC customer;DESC purchase;
自增长 1.一般来说自增长是和primary key配合使用的
2自增长也可以单独使用[但是需要配合一个unique]
3.自增长修饰的字段为整数型的(虽然小数也可以但是非常非常少这样使用)
4.自增长默认从1开始,你也可以通过如下命令修改alter table表名auto_increment=新的开始值;
5.如果你添加数据时,给自增长字段(列)指定的有值,则以指定的值为准,如果指定了自增长,一般来说,就按照自增长的规则来添加数据。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 - - 创建表CREATE TABLE t24(id INT PRIMARY KEY AUTO_INCREMENT, email VARCHAR (32 )NOT NULL DEFAULT '' , `name` VARCHAR (32 )NOT NULL DEFAULT '' ); DESC t24;INSERT INTO t24VALUES (NULL , 'tom@qq.com' , 'tom' );INSERT INTO t24(email, `name`) VALUES ('hsp@sohu.com' , 'hsp' ); SELECT * FROM t24; CREATE TABLE t25(id INT PRIMARY KEY AUTO_INCREMENT, email VARCHAR (32 )NOT NULL DEFAULT '' , `name` VARCHAR (32 )NOT NULL DEFAULT '' ); ALTER TABLE t25 AUTO_INCREMENT = 100 ;INSERT INTO t25VALUES (NULL , 'mary@qq.com' , 'mary' );INSERT INTO t25VALUES (666 , 'hsp@qq.com' , 'hsp' );INSERT INTO t25VALUES (NULL , 'fzy@qq.com' , 'fzy' ); SELECT * FROM t25;
索引 类型
1主键索引,主键自动的为主索引(类型Primary key)
2.唯一索引(UNIQUE)
3.普通索引(INDEX)
4.全文索引 (FULLTEXT)[适用于MylSAM]一般开发,不使用mysql自带的全文索引,而是使用:全文搜索Solr和 ElasticSearch (ES)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 CREATE TABLE t25 (id INT , `name` VARCHAR (32 )); SHOW INDEXES FROM t25;CREATE UNIQUE INDEX id_index ON t25 (id); CREATE INDEX id_index ON t25 (id); ALTER TABLE t25 ADD INDEX id_index (id);CREATE TABLE t26 (id INT , `name` VARCHAR (32 )); ALTER TABLE t26 ADD PRIMARY KEY (id);SHOW INDEX FROM t26;DROP INDEX id_index ON t25;ALTER TABLE t26 DROP PRIMARY KEY;SHOW INDEX FROM t25;SHOW INDEXES FROM t25;SHOW KEYS FROM t25;DESC t25;
事务 事务用于保证数据的一致性,它由一组相关的dml语句组成,该组的dml语句要么全部成功,要么全部失败。如:转账就要用事务来处理,用以保证数据的一致性。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 CREATE TABLE t27( id INT , `name` VARCHAR (32 )); START TRANSACTIONSAVEPOINT aINSERT INTO t27 VALUES (100 , 'tom' );SELECT * FROM t27;SAVEPOINT bINSERT INTO t27 VALUES (200 , 'jack' );ROLLBACK TO bROLLBACK TO aCOMMIT
事务隔离级别 1.多个连接开启各自事务操作数据库中数据时,数据库系统要负责隔离操作,以保证各个连接在获取数据时的准确性。
2.如果不考虑隔离性,可能会引发如下问题:脏读、不可重复读、幻读。
事务 ACID
表类型和存储引擎
MylSAM不支持事务、也不支持外键,但其访问速度快,对事务完整性没有要求
InnoDB存储引擎提供了具有提交、回滚和崩溃恢复能力的事务安全。但是比起MyISAM存储引擎,InnoDB写的处理效率差一些并且会占用更多的磁盘空间以保留数据和索引。
MEMORY存储引擎使用存在内存中的内容来创建表。每个MEMORY表只实际对应上个磁盘文件。MEMORY类型的表访问非常得快,因为它的数据是放在内存中的,并且默认使用HASH索引。但是一旦MySQL服务关闭,表中的数据就会丢失掉,表的结构还在。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 SHOW ENGINES;CREATE TABLE t28 (id INT , `name` VARCHAR (32 )) ENGINE MYISAM START TRANSACTION;SAVEPOINT t1INSERT INTO t28 VALUES (1 , 'jack' );INSERT INTO t28 VALUES (2 , 'bob' );SELECT * FROM t28;ROLLBACK TO t1;CREATE TABLE t29 (id INT , `name` VARCHAR (32 )) ENGINE MEMORY; DESC t29;INSERT INTO t29VALUES (1 ,'tom' ), (2 ,'jack' ), (3 , 'hsp' );SELECT * FROM t29;ALTER TABLE `t29` ENGINE = INNODB;
如何选择表的存储引擎
1.如果你的应用不需要事务,处理的只是基本的CRUD操作,那么MylSAM是不二选择,速度快
2.如果需要支持事务,选择lnnoDB。
3.Memory存储引擎就是将数据存储在内存中,由于没有磁盘I./O的等待,速度极快。但由于是内存存储引擎,所做的任何修改在服务器重启后都将消失。(经典用法用户的在线状态().)
视图 1.视图是根据基表(可以是多个基表)来创建的视图是虚拟的表
2.视图也有列,数据来自基表
3.通过视图可以修改基表的数据
4.基表的改变,也会影响到视图的数据
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 CREATE VIEW emp_view01AS SELECT empno, ename, job, deptno FROM emp; DESC emp_view01;SELECT * FROM emp_view01;SELECT empno, job FROM emp_view01; SHOW CREATE VIEW emp_view01;DROP VIEW emp_view01;UPDATE emp_view01SET job = 'MANAGER' WHERE empno = 7369 ;SELECT * FROM emp; SELECT * FROM emp_view01;UPDATE empSET job = 'SALESMAN' WHERE empno = 7369 ;DESC emp_view01;CREATE VIEW emp_view02AS SELECT empno, ename FROM emp_view01;SELECT * FROM emp_view02;
管理 创建用户
create user ‘用户名’@’允许登录位置’ identified by ‘密码’
说明:创建用户,同时指定密码
删除用户
drop user ‘用户名’ @ ’允许登录位置’ ;
用户修改密码
修改自己的密码:
set password = password(密码’);
修改他人的密码(需要有修改用户密码权限):
set password for ‘用户名’@’登录位置= password(‘密码’);
SET PASSWORD FOR root@localhost = ‘123456’;
权限
给用户授权
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 CREATE USER 'fzy' @'localhost' IDENTIFIED BY '123' CREATE DATABASE testdbCREATE TABLE news (id INT , content VARCHAR (32 )); INSERT INTO news VALUES (100 , '北京新闻' );SELECT * FROM news; GRANT SELECT , INSERT ON testdb.newsTO 'shunping' @'localhost' GRANT UPDATE ON testdb.newsTO 'fzy' @'localhost' ;SET PASSWORD FOR fzy@localhost = 'abc' ;REVOKE SELECT , UPDATE , INSERT ON testdb.news FROM 'fzy' @'localhost' ;REVOKE ALL ON testdb.news FROM 'fzy' @'localhost' ;DROP USER 'fzy' @'localhost' ;
JDBC 1.注册驱动–加载Driver类
2.获取连接–得到Connection
3.执行增删改查-发送SQL给mysql执行
4.释放资源–关闭相关连接
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 import com.mysql.cj.jdbc.Driver;import java.sql.Connection;import java.sql.SQLException;import java.sql.Statement;import java.util.Properties;public class jdbc01 { public static void main (String[] args) throws SQLException { Driver driver = new Driver (); String url = "jdbc:mysql://localhost:3306/fzy_db02" ; Properties properties = new Properties (); properties.setProperty("user" , "root" ); properties.setProperty("password" , "mysql@lmh" ); Connection connect = driver.connect(url, properties); String sql = "delete from actor where id = 1" ; Statement statement = connect.createStatement(); int rows = statement.executeUpdate(sql); System.out.println(rows > 0 ? "成功" : "失败" ); statement.close(); connect.close(); } }
获取数据库连接 方式1
方式2
方式3
方式4 (推荐使用)
方式5
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 package jdbc;import com.mysql.cj.jdbc.Driver;import org.junit.jupiter.api.Test;import java.io.FileInputStream;import java.io.IOException;import java.sql.Connection;import java.sql.DriverManager;import java.sql.SQLException;import java.util.Properties;public class JdbcConn { @Test public void connect01 () throws SQLException { Driver driver = new Driver (); String url = "jdbc:mysql://localhost:3306/hsp_db02" ; Properties properties = new Properties (); properties.setProperty("user" , "root" ); properties.setProperty("password" , "hsp" ); Connection connect = driver.connect(url, properties); System.out.println(connect); } @Test public void connect02 () throws ClassNotFoundException, IllegalAccessException, InstantiationException, SQLException { Class<?> aClass = Class.forName("com.mysql.jdbc.Driver" ); Driver driver = (Driver) aClass.newInstance(); String url = "jdbc:mysql://localhost:3306/hsp_db02" ; Properties properties = new Properties (); properties.setProperty("user" , "root" ); properties.setProperty("password" , "hsp" ); Connection connect = driver.connect(url, properties); System.out.println("方式 2=" + connect); } @Test public void connect03 () throws IllegalAccessException, InstantiationException, ClassNotFoundException, SQLException { Class<?> aClass = Class.forName("com.mysql.jdbc.Driver" ); Driver driver = (Driver) aClass.newInstance(); String url = "jdbc:mysql://localhost:3306/hsp_db02" ; String user = "root" ; String password = "hsp" ; DriverManager.registerDriver(driver); Connection connection = DriverManager.getConnection(url, user, password); System.out.println("第三种方式=" + connection); } @Test public void connect04 () throws ClassNotFoundException, SQLException { Class.forName("com.mysql.jdbc.Driver" ); String url = "jdbc:mysql://localhost:3306/hsp_db02" ; String user = "root" ; String password = "hsp" ; Connection connection = DriverManager.getConnection(url, user, password); System.out.println("第 4 种方式~ " + connection); } @Test public void connect05 () throws IOException, ClassNotFoundException, SQLException { Properties properties = new Properties (); properties.load(new FileInputStream ("src\\mysql.properties" )); String user = properties.getProperty("user" ); String password = properties.getProperty("password" ); String driver = properties.getProperty("driver" ); String url = properties.getProperty("url" ); Class.forName(driver); Connection connection = DriverManager.getConnection(url, user, password); System.out.println("方式 5 " + connection); } }
Statement
PreparedStatement
好处
1.不再使用+拼接sql语句,减少语法错误
2.有效的解决了sql注入问题!
3.大大减少了编译次数,效率较高
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 import java.io.FileInputStream;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.util.Properties;import java.util.Scanner;public class PreparedStatement_ { public static void main (String[] args) throws Exception { Scanner scanner = new Scanner (System.in); System.out.print("请输入管理员的名字: " ); String admin_name = scanner.nextLine(); System.out.print("请输入管理员的密码: " ); String admin_pwd = scanner.nextLine(); Properties properties = new Properties (); properties.load(new FileInputStream ("jdbc\\mysql.properties" )); String user = properties.getProperty("user" ); String password = properties.getProperty("password" ); String driver = properties.getProperty("driver" ); String url = properties.getProperty("url" ); Class.forName(driver); Connection connection = DriverManager.getConnection(url, user, password); String sql = "select name , pwd from admin where name =? and pwd = ?" ; PreparedStatement preparedStatement = connection.prepareStatement(sql); preparedStatement.setString(1 , admin_name); preparedStatement.setString(2 , admin_pwd); ResultSet resultSet = preparedStatement.executeQuery(); if (resultSet.next()) { System.out.println("恭喜, 登录成功" ); } else { System.out.println("对不起,登录失败" ); } resultSet.close(); preparedStatement.close(); connection.close(); } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 import java.io.FileInputStream;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.util.Properties;public class PreparedStatement_ { public static void main (String[] args) throws Exception { Properties properties = new Properties (); properties.load(new FileInputStream ("jdbc\\mysql.properties" )); String user = properties.getProperty("user" ); String password = properties.getProperty("password" ); String driver = properties.getProperty("driver" ); String url = properties.getProperty("url" ); Class.forName(driver); Connection connection = DriverManager.getConnection(url, user, password); String sql = "select * from admin" ; PreparedStatement preparedStatement = connection.prepareStatement(sql); ResultSet resultSet = preparedStatement.executeQuery(); while (resultSet.next()) { System.out.println(resultSet.getString(1 ) + " " + resultSet.getString(2 )); } preparedStatement.close(); connection.close(); } }
API小结
封装 JDBCUtils 在jdbc操作中,获取连接和释放资源是经常使用到,可以将其封装JDBC连接的工具类JDBCUtils
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 import java.io.FileInputStream;import java.io.IOException;import java.sql.*;import java.util.Properties;public class JDBCUtils { private static String user; private static String password; private static String url; private static String driver; static { try { Properties properties = new Properties (); properties.load(new FileInputStream ("jdbc\\mysql.properties" )); user = properties.getProperty("user" ); password = properties.getProperty("password" ); url = properties.getProperty("url" ); driver = properties.getProperty("driver" ); } catch (IOException e) { throw new RuntimeException (e); } } public static Connection getConnection () { try { return DriverManager.getConnection(url, user, password); } catch (SQLException e) { throw new RuntimeException (e); } } public static void close (ResultSet set, Statement statement, Connection connection) { try { if (set != null ) { set.close(); } if (statement != null ) { statement.close(); } if (connection != null ) { connection.close(); } } catch (SQLException e) { throw new RuntimeException (e); } } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 import org.junit.jupiter.api.Test;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;public class JDBCUtils_Use { public static void main (String[] args) { } @Test public void testSelect () { Connection connection = JDBCUtils.getConnection(); String sql = "select * from actor where id = ? " ; PreparedStatement preparedStatement = null ; ResultSet resultSet = null ; try { preparedStatement = connection.prepareStatement(sql); preparedStatement.setInt(1 , 1 ); resultSet = preparedStatement.executeQuery(); while (resultSet.next()) { System.out.println(resultSet.getString(2 )); } } catch (SQLException e) { throw new RuntimeException (e); } finally { JDBCUtils.close(resultSet, preparedStatement, connection); } } @Test public void testDML () { Connection connection = JDBCUtils.getConnection(); PreparedStatement preparedStatement = null ; String sql = "update actor set name = ? where id = ? " ; try { preparedStatement = connection.prepareStatement(sql); preparedStatement.setString(1 , "王菲" ); preparedStatement.setInt(2 , 1 ); preparedStatement.executeUpdate(); } catch (SQLException e) { throw new RuntimeException (e); } finally { JDBCUtils.close(null , preparedStatement, connection); } } }
事务
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 import jdbc.utils.JDBCUtills;import org.junit.jupiter.api.Test;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.SQLException;public class Transaction_ { public static void main (String[] args) { } @Test public void noTransaction () { Connection connection = null ; PreparedStatement preparedStatement = null ; String sql = "update account set balance = balance -100 where id = 1" ; String sql2 = "update account set balance = balance -100 where id = 1" ; try { connection = JDBCUtills.getConnection(); preparedStatement = connection.prepareStatement(sql); preparedStatement.executeUpdate(); int i = 1 / 0 ; preparedStatement = connection.prepareStatement(sql2); preparedStatement.executeUpdate(); } catch (SQLException e) { throw new RuntimeException (e); } finally { JDBCUtills.close(null , preparedStatement, connection); } } @Test public void useTransaction () throws SQLException { Connection connection = null ; PreparedStatement preparedStatement = null ; String sql = "update account set balance = balance -100 where id = 1" ; String sql2 = "update account set balance = balance +100 where id = 2" ; try { connection = JDBCUtills.getConnection(); connection.setAutoCommit(false ); preparedStatement = connection.prepareStatement(sql); preparedStatement.executeUpdate(); preparedStatement = connection.prepareStatement(sql2); preparedStatement.executeUpdate(); connection.commit(); System.out.println("提交" ); } catch (Exception e) { System.out.println("发生错误,回滚" ); connection.rollback(); throw new RuntimeException (e); } finally { JDBCUtills.close(null , preparedStatement, connection); } } }
批处理
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 import jdbc.utils.JDBCUtils;import org.junit.jupiter.api.Test;import java.sql.Connection;import java.sql.PreparedStatement;public class Batch_ { public static void main (String[] args) { } @Test public void batch () throws Exception { Connection connection = JDBCUtils.getConnection(); String sql = "insert into admin2 values(null, ?, ?)" ; PreparedStatement preparedStatement = connection.prepareStatement(sql); System.out.println("开始执行" ); long start = System.currentTimeMillis(); for (int i = 0 ; i < 5000 ; i++) { preparedStatement.setString(1 , "jack" + i); preparedStatement.setString(2 , "666" ); preparedStatement.addBatch(); if ((i + 1 ) % 1000 == 0 ) { preparedStatement.executeBatch(); preparedStatement.clearBatch(); } } long end = System.currentTimeMillis(); System.out.println("批量方式 耗时=" + (end - start)); JDBCUtils.close(null , preparedStatement, connection); } }
数据库连接池
数据库连接池种类
C3P0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 @Test public void testC3P0_01 () throws Exception { ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource (); Properties properties = new Properties (); properties.load(new FileInputStream ("jdbc\\mysql.properties" )); String user = properties.getProperty("user" ); String password = properties.getProperty("password" ); String url = properties.getProperty("url" ); String driver = properties.getProperty("driver" ); comboPooledDataSource.setDriverClass(driver); comboPooledDataSource.setJdbcUrl(url); comboPooledDataSource.setUser(user); comboPooledDataSource.setPassword(password); comboPooledDataSource.setInitialPoolSize(10 ); comboPooledDataSource.setMaxPoolSize(50 ); long start = System.currentTimeMillis(); for (int i = 0 ; i < 5000 ; i++) { Connection connection = comboPooledDataSource.getConnection(); connection.close(); } long end = System.currentTimeMillis(); System.out.println("c3p0 5000 连接 mysql 耗时=" + (end - start)); } @Test public void testC3P0_02 () throws SQLException { ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource ("my-config" ); long start = System.currentTimeMillis(); System.out.println("开始执行...." ); for (int i = 0 ; i < 500000 ; i++) { Connection connection = comboPooledDataSource.getConnection(); System.out.println("连接 OK~" ); connection.close(); } long end = System.currentTimeMillis(); System.out.println("c3p0 的第二种方式(500000) 耗时=" + (end - start)); }
Druid 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 @Test public void testDruid () throws Exception { Properties properties = new Properties (); properties.load(new FileInputStream ("src\\druid.properties" )); DataSource dataSource = DruidDataSourceFactory.createDataSource(properties); long start = System.currentTimeMillis(); for (int i = 0 ; i < 5000 ; i++) { Connection connection = dataSource.getConnection(); connection.close(); } long end = System.currentTimeMillis(); System.out.println("druid 连接池 操作 500000 耗时=" + (end - start)); }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 import com.alibaba.druid.pool.DruidDataSourceFactory;import javax.sql.DataSource;import java.io.FileInputStream;import java.sql.Connection;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;import java.util.Properties;public class JDBCUtilsByDruid { private static DataSource ds; static { Properties properties = new Properties (); try { properties.load(new FileInputStream ("src\\druid.properties" )); ds = DruidDataSourceFactory.createDataSource(properties); } catch (Exception e) { throw new RuntimeException (e); } } public static Connection getConnection () throws SQLException { return ds.getConnection(); } public static void close (ResultSet rs, Statement st, Connection c) { try { if (rs != null ) { rs.close(); } if (st != null ) { st.close(); } if (c != null ) { c.close(); } } catch (SQLException e) { throw new RuntimeException (e); } } }
Apache—DBUtils
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 import org.apache.commons.dbutils.QueryRunner;import org.apache.commons.dbutils.handlers.BeanHandler;import org.apache.commons.dbutils.handlers.BeanListHandler;import org.apache.commons.dbutils.handlers.ScalarHandler;import org.junit.jupiter.api.Test;import java.sql.Connection;import java.sql.SQLException;import java.util.List;public class DBUtils_USE { @Test public void testQueryMany () throws SQLException { Connection connection = JDBCUtilsByDruid.getConnection(); QueryRunner queryRunner = new QueryRunner (); String sql = "select id, name from actor where id >= ?" ; List<Actor> list = queryRunner.query(connection, sql, new BeanListHandler <>(Actor.class), 1 ); System.out.println("输出集合的信息" ); for (Actor actor : list) { System.out.println(actor); } JDBCUtilsByDruid.close(null , null , connection); } @Test public void testQuerySingle () throws SQLException { Connection connection = JDBCUtilsByDruid.getConnection(); QueryRunner queryRunner = new QueryRunner (); String sql = "select * from actor where id = ?" ; Actor actor = queryRunner.query(connection, sql, new BeanHandler <>(Actor.class), 2 ); System.out.println(actor); JDBCUtilsByDruid.close(null , null , connection); } @Test public void testScalar () throws SQLException { Connection connection = JDBCUtilsByDruid.getConnection(); QueryRunner queryRunner = new QueryRunner (); String sql = "select name from actor where id = ?" ; Object obj = queryRunner.query(connection, sql, new ScalarHandler (), 1 ); System.out.println(obj); JDBCUtilsByDruid.close(null , null , connection); } @Test public void testDML () throws SQLException { Connection connection = JDBCUtilsByDruid.getConnection(); QueryRunner queryRunner = new QueryRunner (); String sql = "delete from actor where id = ?" ; int affectedRow = queryRunner.update(connection, sql, 1000 ); System.out.println(affectedRow > 0 ? "执行成功" : "执行没有影响到表" ); JDBCUtilsByDruid.close(null , null , connection); } }
BasicDao