文章目录
10-JDBC (重点)
10.1, 下载mysql-connector-java
Maven Repository: mysql » mysql-connector-java (mvnrepository.com)
阿里云盘: jar包下载
选择想要的版本
下载jar
10.2, 第一个JDBC程序
1, 创建测试数据库
CREATE DATABASE `jdbcStudy` CHARACTER SET utf8 COLLATE utf8_general_ci;
USE `jdbcStudy`;
CREATE TABLE `users`(
`id` INT PRIMARY KEY,
`NAME` VARCHAR(40),
`PASSWORD` VARCHAR(40),
`email` VARCHAR(60),
birthday DATE
);
INSERT INTO `users`(`id`,`NAME`,`PASSWORD`,`email`,`birthday`)
VALUES(1,'zhangsan','123456','zs@sina.com','1980-12-04'),
(2,'lisi','123456','lisi@sina.com','1981-12-04'),
(3,'wangwu','123456','wangwu@sina.com','1979-12-04')
2, 创建一个普通项目
3,导入数据库驱动
项目下新建lib目录, 把jar包复制进去
add as library
4,连接数据库
package com.ccc.lesson01;
import java.sql.*;
public class JdbcFirst {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//1 加载驱动
Class.forName("com.mysql.jdbc.Driver"); //固定写法, 加载驱动
//2 用户信息和URL
String url = "jdbc:mysql://192.168.0.201:3306/jdbcstudy?useUnicode=true&characterEncoding=utf8&useSSL=true";
String username = "root";
String pwd = "123456";
//3 连接成功, 数据库对象
// Connection 代表数据库
Connection connection = DriverManager.getConnection(url, username, pwd);
//4 执行SQL对象 statement
Statement statement = connection.createStatement();
//5 对象执行SQL
String sql = "select * from users";
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()){
System.out.println("id="+resultSet.getObject("id"));
System.out.println("name="+resultSet.getObject("NAME"));
System.out.println("pwd="+resultSet.getObject("PASSWORD"));
System.out.println("email="+resultSet.getObject("email"));
System.out.println("birth="+resultSet.getObject("birthday"));
}
//6 释放连接
resultSet.close();
statement.close();
connection.close();
}
}
步骤:
- 加载驱动
- 连接数据库, DriverManager
- 获得执行SQL的对象 statement
- 获得返回结果集
- 释放连接
连接报错:
需把URL修改为useSSL=false
时区的错误添加&serverTimezone=GMT%2B8
10.3对象
DriverManager
//DriverManager.registerDriver(new com.mysql.jdbc.Driver());
Class.forName("com.mysql.jdbc.Driver"); //固定写法, 加载驱动
第一种注册了两次不建议使用
//数据库对象
Connection connection = DriverManager.getConnection(url, username, pwd);
//事物回滚
connection.rollback();
//事物提交
connection.commit();
//数据库自动提交
connection.setAutoCommit();
URL
String url = "jdbc:mysql://192.168.0.201:3306/jdbcstudy?useUnicode=true&characterEncoding=utf8&useSSL=false";
// mysql -- 3306
jdbc:mysql://主机地址:端口/数据库名?参数1&2&3
// Oracle
jdbc:oracle:thin:@localhost:1521:sid
Statement 执行SQL的对象 PrepareStatement
Statement statement = connection.createStatement();
//编写SQL
String sql = "select * from users";
//执行查询
statement.executeQuery(sql);
//更新,插入,删除, 返回影响行数
statement.executeUpdate(sql);
//执行任何SQL
statement.execute(sql);
ResultSet 查询结果集
ResultSet resultSet = statement.executeQuery(sql);
获得指定数据类型
//不知道类型使用object
resultSet.getObject("id");
//知道类型使用对应类型
resultSet.getInt("id");
遍历, 指针
resultSet.beforeFirst();//移动到最前面
resultSet.afterLast();//移动到最后面
resultSet.next();//移动到下一个
resultSet.previous();//移动到前一个
resultSet.absolute(row);//移动到指定行
10.4, statement对象
Jdbc中的statement对象用于向数据库发送SQL语句,想完成对数据库的增删改查,只需要通过这个对象向数据库发送增删
改查语句即可。
1编写工具类
package com.ccc.lesson2util;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
public class JdbcUtil {
private static String driver = null;
private static String url = null;
private static String username = null;
private static String password = null;
static {
try {
InputStream inputStream = JdbcUtil.class.getClassLoader().getResourceAsStream("db.properties");
Properties properties = new Properties();
properties.load(inputStream);
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, ResultSet rs, Statement st){
if (conn!=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (st!=null){
try {
st.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (rs!=null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
2增删改测试
package com.ccc.lesson2util;
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 connection =null;
Statement st = null;
ResultSet rs = null;
try {
connection = JdbcUtil.getConnection();//数据库连接
st = connection.createStatement();//获得执行对象
//增
// String sql = "insert into users(id,`name`,`password`,`email`,`birthday`) values(4,'zs','123456','111@qq.com','2022-02-02')" ;
//删
// String sql = "delete from users WHERE id = 4;";
//改
String sql = "update users set `NAME` = 'zs',`PASSWORD`='123421' where id = 1;";
int i = st.executeUpdate(sql);
if (i>0){
System.out.println("修改成功");
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
JdbcUtil.release(connection,rs,st);
}
}
}
3查询 executeQuery
package com.ccc.lesson2util;
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 connection = null;
Statement statement = null;
ResultSet resultSet = null;
try {
connection= JdbcUtil.getConnection();
statement = connection.createStatement();
String sql = "select * from users";
resultSet = statement.executeQuery(sql);
while (resultSet.next()){
System.out.print(resultSet.getInt("id")+", ");
System.out.print(resultSet.getString("name")+", ");
System.out.print(resultSet.getString("password")+", ");
System.out.print(resultSet.getString("email"));
System.out.println();
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
JdbcUtil.release(connection, resultSet, statement);
}
}
}
4SQL注入
package com.ccc.lesson2util;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class TestSql {
public static void main(String[] args) {
System.out.println(login("zs", "123421")); //true
System.out.println(login("ssb", "ssb")); //false
System.out.println(login("ssb ' or ''='", "ssb' or ''='")); //true
//sql 相当于被改为
//select * from users where `NAME` = 'ssb' or ''='' and `PASSWORD`= 'ssb' or ''='';
}
private static boolean login(String name, String pwd) {
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
try {
connection= JdbcUtil.getConnection();
statement = connection.createStatement();
String sql = "select * from users where `NAME` = '"+name+"' and `PASSWORD`= '"+pwd+"';";
resultSet = statement.executeQuery(sql);
if (resultSet.next()){
return true;
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
JdbcUtil.release(connection, resultSet, statement);
}
return false;
}
}
解决方式, Statement对象改使用PreparedStatement
10.5, PreparedStatement对象
PreparedStatement可以防止SQL注入, 效率更高
增删改
package com.ccc.lesson3;
import com.ccc.lesson2util.JdbcUtil;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class TestPdInsert {
public static void main(String[] args) {
Connection connection =null;
PreparedStatement pds =null;
try {
connection = JdbcUtil.getConnection();
//区别, 使用? 占位符代替参数
String sql = "insert into users(id,`name`,`password`,`email`,`birthday`) values(?,?,?,?,?)";
pds= connection.prepareStatement(sql); //预编译SQL, 先写SQL不执行
//手动给参数赋值
pds.setInt(1,4);
pds.setString(2,"zs");
pds.setString(3,"4123123");
pds.setString(4,"412@qq.com");
pds.setDate(5,new Date(new java.util.Date().getTime()));
int i = pds.executeUpdate();
if (i>0){
System.out.println("修改成功");
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
JdbcUtil.release(connection,null,pds);
}
}
}
2查询
package com.ccc.lesson3;
import com.ccc.lesson2util.JdbcUtil;
import java.sql.*;
public class TestPdSelect {
public static void main(String[] args) {
Connection connection =null;
PreparedStatement pds =null;
ResultSet rs = null;
try {
connection = JdbcUtil.getConnection();//获取连接
String sql = "select * from users where id = ?";
pds = connection.prepareStatement(sql); //预编译
pds.setInt(1,2);
rs = pds.executeQuery();
while (rs.next()){
System.out.println(rs.getString("name"));
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
JdbcUtil.release(connection,rs,pds);
}
}
}
Statement小结
- 推荐使用PreparedStatement
- 防止SQL注入的本质, 把传递进来的参数当做字符
- 加入中间存在转义字符, 比如’ 会被直接转义
10.6使用IDEA连接mysql
填写连接信息
查看表
修改数据
查询SQL编写
10.7,事务
ACID原则:
-
原子性 要么一起完成, 要么不完成
-
一致性 总数不变
-
隔离性 多个进程互不干扰
-
持久性 一旦提交不可逆, 持久化到数据库
隔离性的问题:
脏读: 一个事务读取了另一个事务没有提交的数据
不可重复读:不能重复读取一个在事务中的数据
幻读: 读取时间不同, 导致数据不一致
四个隔离级别:
读未提交: 可以读取一个事务未提交的数据
读提交: 只能读取已提交的数据
可重复读: 一个事务在读取数据时 不允许修改操作
可序列化: 最高隔离级别, 事务串行化顺序执行
package com.ccc.lesson4;
import com.ccc.lesson2util.JdbcUtil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class TestTransaction {
public static void main(String[] args) {
Connection conn = null;
PreparedStatement pst = null;
ResultSet res = null;
try {
conn = JdbcUtil.getConnection();
conn.setAutoCommit(false);
String sql = "update account set money= money+100 WHERE `name` = 'A';";
pst = conn.prepareStatement(sql);
int i = pst.executeUpdate();
String sql2 = "update account set money= money-100 WHERE `name` = 'B'";
pst = conn.prepareStatement(sql2);
pst.executeUpdate();
conn.commit();
System.out.println("成功");
} catch (SQLException e) {
// 失败回滚
try {
conn.rollback();
} catch (SQLException ex) {
ex.printStackTrace();
}
e.printStackTrace();
}finally {
//恢复自动提交
try {
conn.setAutoCommit(true);
} catch (SQLException e) {
e.printStackTrace();
}
JdbcUtil.release(conn,res,pst);
}
}
}
10.8,数据库连接池
池化技术: 预先准备资源, 使用的时候无需创建, 直接使用
最小连接数: 10 常用连接数
最大连接数: 15 业务最高承载上限
超过最大连接数, 排队等待
等待超时: 1000ms
开源数据源实现
DBCP
C3P0
Druid: 阿里
dbcp
导入jar包
package com.ccc.lesson05util;
import com.ccc.lesson2util.JdbcUtil;
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 DbcpUtils {
private static DataSource dataSource = null;
static {
try {
InputStream inputStream = DbcpUtils.class.getClassLoader().getResourceAsStream("dbcpconfig.properties");
Properties properties = new Properties();
properties.load(inputStream);
//创建数据源
dataSource = BasicDataSourceFactory.createDataSource(properties);
}catch (Exception e){
e.printStackTrace();
}
}
//获取连接
public static Connection getConnection() throws SQLException {
return dataSource.getConnection();
}
//释放连接资源
public static void release(Connection conn, ResultSet rs, Statement st){
if (conn!=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (st!=null){
try {
st.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (rs!=null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
jar包下载(commons-dbcp-1.2.jar , mysql-connector-java-5.1.47.jar):
阿里云盘: jar包下载
狂神Mysql所用到的SQL:
p16-school.SQL
create database if not exists `school`;
-- 创建一个school数据库
use `school`;-- 创建学生表
drop table if exists `student`;
create table `student`(
`studentno` int(4) not null comment '学号',
`loginpwd` varchar(20) default null,
`studentname` varchar(20) default null comment '学生姓名',
`sex` tinyint(1) default null comment '性别,0或1',
`gradeid` int(11) default null comment '年级编号',
`phone` varchar(50) not null comment '联系电话,允许为空',
`address` varchar(255) not null comment '地址,允许为空',
`borndate` datetime default null comment '出生时间',
`email` varchar (50) not null comment '邮箱账号允许为空',
`identitycard` varchar(18) default null comment '身份证号',
primary key (`studentno`),
unique key `identitycard`(`identitycard`),
key `email` (`email`)
)engine=myisam default charset=utf8;
-- 创建年级表
drop table if exists `grade`;
create table `grade`(
`gradeid` int(11) not null auto_increment comment '年级编号',
`gradename` varchar(50) not null comment '年级名称',
primary key (`gradeid`)
) engine=innodb auto_increment = 6 default charset = utf8;
-- 创建科目表
drop table if exists `subject`;
create table `subject`(
`subjectno`int(11) not null auto_increment comment '课程编号',
`subjectname` varchar(50) default null comment '课程名称',
`classhour` int(4) default null comment '学时',
`gradeid` int(4) default null comment '年级编号',
primary key (`subjectno`)
)engine = innodb auto_increment = 19 default charset = utf8;
-- 创建成绩表
drop table if exists `result`;
create table `result`(
`studentno` int(4) not null comment '学号',
`subjectno` int(4) not null comment '课程编号',
`examdate` datetime not null comment '考试日期',
`studentresult` int (4) not null comment '考试成绩',
key `subjectno` (`subjectno`)
)engine = innodb default charset = utf8;
-- 插入学生数据 其余自行添加 这里只添加了2行
insert into `student` (`studentno`,`loginpwd`,`studentname`,`sex`,`gradeid`,`phone`,`address`,`borndate`,`email`,`identitycard`)
values
(1000,'123456','张伟',0,2,'13800001234','北京朝阳','1980-1-1','text123@qq.com','123456198001011234'),
(1001,'123456','赵强',1,3,'13800002222','广东深圳','1990-1-1','text111@qq.com','123456199001011233');
-- 插入成绩数据 这里仅插入了一组,其余自行添加
insert into `result`(`studentno`,`subjectno`,`examdate`,`studentresult`)
values
(1000,1,'2013-11-11 16:00:00',85),
(1000,2,'2013-11-12 16:00:00',70),
(1000,3,'2013-11-11 09:00:00',68),
(1000,4,'2013-11-13 16:00:00',98),
(1000,5,'2013-11-14 16:00:00',58);
-- 插入年级数据
insert into `grade` (`gradeid`,`gradename`) values(1,'大一'),(2,'大二'),(3,'大三'),(4,'大四'),(5,'预科班');
-- 插入科目数据
insert into `subject`(`subjectno`,`subjectname`,`classhour`,`gradeid`)values
(1,'高等数学-1',110,1),
(2,'高等数学-2',110,2),
(3,'高等数学-3',100,3),
(4,'高等数学-4',130,4),
(5,'C语言-1',110,1),
(6,'C语言-2',110,2),
(7,'C语言-3',100,3),
(8,'C语言-4',130,4),
(9,'Java程序设计-1',110,1),
(10,'Java程序设计-2',110,2),
(11,'Java程序设计-3',100,3),
(12,'Java程序设计-4',130,4),
(13,'数据库结构-1',110,1),
(14,'数据库结构-2',110,2),
(15,'数据库结构-3',100,3),
(16,'数据库结构-4',130,4),
(17,'C#基础',130,1);
P21 自连接
CREATE TABLE category (
categoryid INT(10) UNSIGNED NOT NULL auto_increment COMMENT '主题ID',
pid INT(10) NOT NULL COMMENT '父ID',
categoryName VARCHAR(50) NOT NULL COMMENT '主题名字',
PRIMARY KEY(categoryid)
) ENGINE=INNODB auto_increment=9 DEFAULT CHARSET = utf8;
INSERT INTO category(categoryid,pid,categoryName)
VALUES('2','1','信息技术'),('3','1','软件开发'),('4','3','数据库'),
('5','1','美术设计'),('6','3','web开发'),('7','5','PS技术'),('8','2','办公信息');
P29 shop
-- 转账
CREATE DATABASE shop CHARACTER SET utf8 COLLATE utf8_general_ci;
use shop;
CREATE TABLE `account`(
`id` int(3) 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);
P31 app_user, 100万数据
CREATE TABLE `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,
`update_time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8 COMMENT = 'app用户表'
-- 插入100万数据.
DROP FUNCTION IF EXISTS mock_data;
-- 写函数之前必须要写,标志:$$
DELIMITER $$
CREATE FUNCTION mock_data()
RETURNS INT
-- 注意returns,否则报错。
BEGIN
DECLARE num INT DEFAULT 1000000;
-- num 作为截止数字,定义为百万,
DECLARE i INT DEFAULT 0;
WHILE i < num DO
INSERT INTO app_user(`name`, `email`, `phone`, `gender`, `password`, `age`)
VALUES(CONCAT('用户', i), CONCAT('100',i,'@qq.com'), CONCAT('13', FLOOR(RAND()*(999999999-100000000)+100000000)),FLOOR(RAND()*2),UUID(), FLOOR(RAND()*100));
SET i = i + 1;
END WHILE;
RETURN i;
END;
SELECT mock_data () -- 执行此函数 生成一百万条数据
P38 建表 jdbcstudy
CREATE DATABASE `jdbcStudy` CHARACTER SET utf8 COLLATE utf8_general_ci;
USE `jdbcStudy`;
CREATE TABLE `users`(
`id` INT PRIMARY KEY,
`NAME` VARCHAR(40),
`PASSWORD` VARCHAR(40),
`email` VARCHAR(60),
birthday DATE
);
INSERT INTO `users`(`id`,`NAME`,`PASSWORD`,`email`,`birthday`)
VALUES(1,'zhangsan','123456','zs@sina.com','1980-12-04'),
(2,'lisi','123456','lisi@sina.com','1981-12-04'),
(3,'wangwu','123456','wangwu@sina.com','1979-12-04')
P45 DBCP配置文件
DBCP配置文件
#连接设置
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/jdbcstudy?useUnicode=true&characterEncoding=utf8&useSSL=true
username=root
password=123456
#<!-- 初始化连接 -->
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=true
#driver default 指定由连接池所创建的连接的事务级别(TransactionIsolation)。
#可用值为下列之一:(详情可见javadoc。)NONE,READ_UNCOMMITTED, READ_COMMITTED, REPEATABLE_READ, SERIALIZABLE
defaultTransactionIsolation=READ_COMMITTED