JDBC
java database connection 规范,API,接口。
jdbc与数据库驱动的关系,就是接口与实现的关系。
1、快速入门JDBC
1.1、准备好数据库与数据库表
create table user(
id int primary key auto_increment,
username varchar(20),
password varchar(20),
nickname varchar(20)
);
INSERT INTO `USER` VALUES(null,'zs','123456','老张');
INSERT INTO `USER` VALUES(null,'ls','123456','老李');
INSERT INTO `USER` VALUES(null,'wangwu','123','东方不败');
1.2、创建一个JAVA工程
maven 创建我们的java项目,包(jar包)统一管理。
pom.xml
修改pom.xml里面的配置文件,必须重新更新(reload project)。
jdbc_demo_01
1.3、准备好驱动jar包
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.28</version>
</dependency>
1.4、编写代码
(1)加载驱动
DriverManager.registerDriver(new Driver());
(2)创建数据库连接
url格式:jdbc:mysql://ip:port/dbname
String url="jdbc:mysql://localhost:3306/数据库名";
String username="root";
String password="Root123456";
Connection connection=DriverManager.getConnection(url,username,password);
(3)操作数据库表
需求:查询user表中所有的记录
A、准备好查询的SQL
String sql="select * from user";
B、创建执行SQL的对象
Statement statement=connection.createStatement();
C、执行SQL,得到结果集
ResultSet resultSet=statement.executeQuery(sql);
D、展示查询出来的结果
while(resultSet.next()){
System.out.print(resultSet.getObject(1)+" ");
System.out.print(resultSet.getObject(2)+" ");
System.out.print(resultSet.getObject(3)+" ");
System.out.print(resultSet.getObject(4)+" ");
System.out.println();
}
(4)释放资源
resultSet.close();
statement.close();
connection.close();
案例:
public class JdbcTest {
public static void main(String[] args) throws SQLException {
//1、加载驱动
DriverManager.registerDriver(new Driver());
//2、连接数据库
//声明url,username,password
String url="jdbc:mysql://localhost:3306/db02";
String username="root";
String password="Root123456";
Connection connection=DriverManager.getConnection(url,username,password);
//3、操作数据库表
String sql="select * from user";
Statement statement=connection.createStatement();
ResultSet resultSet=statement.executeQuery(sql);
//循环打印出所有记录(结果集)
while(resultSet.next()){
System.out.print(resultSet.getObject(1)+" ");
System.out.print(resultSet.getObject(2)+" ");
System.out.print(resultSet.getObject(3)+" ");
System.out.print(resultSet.getObject(4)+" ");
System.out.println();
}
//4、释放资源(先创建,后关闭)
resultSet.close();
statement.close();
connection.close();
}
}
2、JDBC API详解
2.1、DriverManager
加载驱动
DriverManager.registerDriver(new Driver())
mysql8.jar com.mysql.cj.jdbc.Driver
mysql5.jar com.mysql.jdbc.Driver
Class.forName("com.mysql.cj.jdbc.Driver"); //反射机制
创建连接
DriverManager.getConnection(url,username,password)
url地址连接mysql格式:
jdbc:mysql://ip地址:端口号/数据库名
jdbc:mysql://localhost:3306/db02
jdbc:mysql://…/db02
2.2、Connection
是数据库连接对象。
Statement<=createStatement() 创建执行SQL语句对象
拿到SQL语句就只能直接执行。
例:
Connection conn=DriverManager.getConnection(url,username,password);
Statement state=conn.createStatement();
PreparedStatement<=prepareStatement() 创建预编译执行SQL语句对象
拿到SQL语句可以先编译,在执行。
例:
Connection conn=DriverManager.getConnection(url,username,password);
PreparedStatement state=conn.prepareStatement();
2.3、Statement
直接执行写好的SQL语句。
executeQuery(sql) 只能执行DQL语句,select查询语句
例:
String sql=“select * from user”;
Connection conn=DriverManager.getConnection(url,username,password);
Statement state=conn.createStatement();
ResultSet rs=state.executeQuery(sql);
executeUpdate(sql) 只能执行DML语句,insert update delete语句
例:
String sql=“delete from user where id=1”;
Connection conn=DriverManager.getConnection(url,username,password);
Statement state=conn.createStatement();
state.executeUpdate(sql);
execute() 执行任意语句,返回true/false
例1:
String sql=“select * from user”;
Connection conn=DriverManager.getConnection(url,username,password);
Statement state=conn.createStatement();
Boolean isval=state.execute(sql);
注意:
isval为true,表示查询到了用户记录
isval为false,表示没有查询到用户记录
例2:
String sql=“delete from user where id=1”;
Connection conn=DriverManager.getConnection(url,username,password);
Statement state=conn.createStatement();
Boolean isval=state.execute(sql);
注意:
isval为false,增加语句、修改语句、删除语句没有结果集
2.4、ResultSet
对象,结果集
next() 方法:游标往下移一行,判断是否存在记录,存在就用get方法来取值
get方法:
getInt(int i) i表示的是位置 getInt(String name) name表示的是字段名
getString()
getDouble()
getBoolean()
getDate()
……
例:
String sql=“select * from user”;
Connection conn=DriverManager.getConnection(url,username,password);
Statement state=conn.createStatement();
ResultSet rs=state.executeQuery(sql);
while(rs.next()){
System.out.println(rs.getInt(1));
System.out.println(rs.getInt(“id”));
}
2.5、PreparedStatement
预编译执行SQL对象? 替换符
案例:
@Test
public void demo01() throws SQLException {
int id=3;
String sql="select * from user where id=?";
//1、获取连接
Connection connection=JdbcUtils.getConnection();
//2、获取预编译执行SQL对象
PreparedStatement ps=connection.prepareStatement(sql);
ps.setInt(1,id);
//3、执行SQL
ResultSet rs=ps.executeQuery();
//4、结果集存入到实体类,实体类存入到集合
List<User> list=new ArrayList<User>();
while(rs.next()){
User user=new User();
user.setId(rs.getInt("id"));
user.setUsername(rs.getString("username"));
user.setPassword(rs.getString("password"));
user.setNickname(rs.getString("nickname"));
list.add(user);
}
//展示集合中存放的结果集。
for(User u:list){
System.out.println(u.toString());
}
}
案例:
public class JdbcTest {
public static void main(String[] args) throws SQLException, ClassNotFoundException {
//1、加载驱动
// DriverManager.registerDriver(new Driver());
Class.forName("com.mysql.cj.jdbc.Driver"); //反射机制
//2、连接数据库
//声明url,username,password
String url="jdbc:mysql://localhost:3306/db02";
String username="root";
String password="Root123456";
Connection connection=DriverManager.getConnection(url,username,password);
//3、操作数据库表
String sql="select * from user";
Statement statement=connection.createStatement();
ResultSet resultSet=statement.executeQuery(sql);
//循环打印出所有记录(结果集)
while(resultSet.next()){
System.out.print(resultSet.getObject("id")+" ");
System.out.print(resultSet.getObject("username")+" ");
System.out.print(resultSet.getObject("nickname")+" ");
System.out.print(resultSet.getObject("password")+" ");
System.out.println();
}
//4、释放资源(先创建,后关闭)
resultSet.close();
statement.close();
connection.close();
}
}
3、操作数据库(CRUD)
3.1、单元测试
JUnit 导入依赖
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.1</version>
<scope>test</scope>
</dependency>
代码:
public class JdbcDemo01 {
@Test
public void selectSql(){
System.out.println("单元测试");
}
@Test
public void selectUpdate(){
}
}
3.2、CRUD
步骤:
加载驱动
获取连接
创建SQL执行对象(CRUD)
执行SQL
释放资源
//增加、修改、删除
public class JdbcDemo02 {
//增加
@Test
public void insertUser() throws ClassNotFoundException, SQLException {
String insert_sql="insert into user values(null,'lisi','lisi12345','李四')";
String url="jdbc:mysql://localhost:3306/db02";
String username="root";
String password="Root123456";
Class.forName("com.mysql.cj.jdbc.Driver");
Connection connection= DriverManager.getConnection(url,username,password);
Statement statement=connection.createStatement();
statement.executeUpdate(insert_sql);
statement.close();
connection.close();
}
//修改
@Test
public void updateUser() throws ClassNotFoundException, SQLException {
String updata_sql="update user set nickname='李五' where id=4";
String url="jdbc:mysql://localhost:3306/db02";
String username="root";
String password="Root123456";
Class.forName("com.mysql.cj.jdbc.Driver");
Connection connection= DriverManager.getConnection(url,username,password);
Statement statement=connection.createStatement();
statement.executeUpdate(updata_sql);
statement.close();
connection.close();
}
//删除
@Test
public void deleteUser() throws ClassNotFoundException, SQLException {
String delete_sql="delete from user where id=4";
String url="jdbc:mysql://localhost:3306/db02";
String username="root";
String password="Root123456";
Class.forName("com.mysql.cj.jdbc.Driver");
Connection connection= DriverManager.getConnection(url,username,password);
Statement statement=connection.createStatement();
statement.executeUpdate(delete_sql);
statement.close();
connection.close();
}
}
登录案例:
(1)分析
用一个登录页面;
去查询数据库判断有没有输入的用户和密码;
有就输出登录成功,没有就输出登录失败
(2)前期准备
输出流、输入流
数据库、数据库表、Jdbc工具类、JdbcAPI
(3)代码步骤
(3-1)idea新建maven项目
(3-2)导入依赖,mysql,junit
(3-3)创建实体类User
(3-4)创建配置文件jdbc.properties
(3-5)创建工具类JdbcUtils.java
(3-6)创建一个登录类
(3-6-1)创建输出页面的方法
(3-6-2)输入用户密码和密码
(3-6-3)去数据库查询用户名和密码是否存在
(3-6-4)存在,就输出登录成功!,不存在就输出登录失败
public class JdbcLogin {
public static void main(String args[]) throws SQLException {
Scanner scanner=new Scanner(System.in);
System.out.println("请输入用户名:");
String username=scanner.next();
System.out.println("请输入密码:");
String password=scanner.next();
//去数据库里面查看用户名是否存在
String sql ="select * from user where username=? and password=?";
//去数据库查询用户名和密码
//1、获取连接
Connection connection=JdbcUtils.getConnection();
//2、创建预编译对象
PreparedStatement preparedStatement=connection.prepareStatement(sql);
//3、替换替换符内容
preparedStatement.setString(1,username);
preparedStatement.setString(2,password);
//4、执行SQL得到结果集
ResultSet resultSet=preparedStatement.executeQuery();
//5、得到是否登录成功,成功就是为true,失败为False
boolean isval = false;
if(resultSet.next()){
isval = true;
}
//6、释放资源
JdbcUtils.closeAll(resultSet,preparedStatement,connection);
if(isval){
System.out.println("登录成功!");
}else{
System.out.println("登录失败!");
}
}
}
4、JDBC事务
setAutoCommit() false,表示关闭自动提交;true,开启自动提交事务;
commit()
rollback()
public class JdbcDemo03 {
//修改,增加事务步骤
@Test
public void updateUser(){
//1、修改SQL语句
String sql="update user set nickname=? where id=?";
//2、获取连接
Connection connection= JdbcUtils.getConnection();
PreparedStatement preparedStatement= null;
try {
//事务---开启事务---把事务从自动,调整为手动提交
connection.setAutoCommit(false);
//3、创建PreparedStatement对象
preparedStatement = connection.prepareStatement(sql);
//4、替换替换符
preparedStatement.setString(1,"小李子22222");
preparedStatement.setInt(2,2);
//5、执行SQL
preparedStatement.executeUpdate();//********
//事务---结束事务---事务提交
connection.commit();
} catch (SQLException e) {
try {
//事务---结束事务---事务回滚
connection.rollback();
} catch (SQLException ex) {
throw new RuntimeException(ex);
}
} finally {
//6、释放资源
JdbcUtils.closeAll(null,preparedStatement,connection);
}
}
}
转账案例:
1、准备数据库表
account
2、需求
zs给ls转了100
3、分析
zs要从他的帐号里面扣出100
ls要往他的帐号增加100
4、代码
//转账,通过事务实现
@Test
public void zhuangZhang(){
//1、准备好SQL
String sql="update account set money=money+? where uname=?";
// update account set money=money+(-100) where uname='zs';
// update account set money=money+100 where uname='ls';
//获取连接
Connection connection=JdbcUtils.getConnection();
PreparedStatement preparedStatement01=null;
PreparedStatement preparedStatement02=null;
try {
//开启手动提交事务
connection.setAutoCommit(false);
//创建预编译对象
preparedStatement01=connection.prepareStatement(sql);
preparedStatement02=connection.prepareStatement(sql);
//替换替换符
preparedStatement01.setDouble(1,-100);
preparedStatement01.setString(2,"zs");
preparedStatement02.setDouble(1,100);
preparedStatement02.setString(2,"ls");
//执行
preparedStatement01.executeUpdate();
preparedStatement02.executeUpdate();
//
// int i=1;
// i=i/0;
connection.commit();
} catch (SQLException e) {
try {
connection.rollback();
} catch (SQLException ex) {
throw new RuntimeException(ex);
}
} finally {
JdbcUtils.closeAll(null,preparedStatement01,null);
JdbcUtils.closeAll(null,preparedStatement02,connection);
}
}
5、连接池
5.1、连接池概述
5.1.1、为什么要去使用连接池
存放多个连接的容器。
我会频繁的使用连接,一个连接从创建到销毁都会消耗我们的资源。
同时创建多个连接,存入集合,使用获取集合中没有被使用的连接,使用完后就将连接归还给集合。
5.1.2、连接池原理
如果连接池中基础连接被获取完了,要么等待3S,看是否有连接归还;如果没有就只能新建连接。
自定义连接池,使用的是LinkedList集合来存放我们的连接。
5.2、自定义连接池
创建类,连接池类(MyDataSource.java)
定义一个集合对象(LinkedList.java)
初始化连接,5个、10个
获取连接
归还连接
//1、新建连接池类
public class MyDataSource {
//2、创建连接池
private LinkedList<Connection> connectionPool=new LinkedList<Connection>();
//3、初实始化5个连接
public MyDataSource(){
for(int i=1;i<=5;i++){
//创建5个连接
Connection connection=JdbcUtils.getConnection();
connectionPool.add(connection);
}
}
//4、获取连接,还有初始化好的连接就获取,没有子就创建新的连接
public Connection getConnection(){
Connection connection=null;
if(connectionPool.size()>0){
connection =connectionPool.removeFirst();
}else{
connection=JdbcUtils.getConnection();
}
return connection;
}
//5、归还连接,就是将使用完的连接,在次存入到我们的连接池对象
public void addBack(Connection connection){
connectionPool.addLast(connection);
}
}
6、连接池使用
@Test
public void selectAllUser() throws SQLException {
//1、查询所有SQL语句
String sql="select * from user";
//2、获取连接
MyDataSource myDataSource=new MyDataSource();//new 时已经初始化有5个连接
Connection connection=myDataSource.getConnection();//获取连接
//3、创建PreparedStatement对象
PreparedStatement preparedStatement=connection.prepareStatement(sql);
//4、替换替换符(无参数)
//5、执行SQL,拿到结果集
ResultSet resultSet=preparedStatement.executeQuery();
//6、取出结果集,存入到实体类;实体类存入到集合
List<User> list=new ArrayList<User>();
while(resultSet.next()){
User user=new User();
user.setId(resultSet.getInt("id"));
user.setUsername(resultSet.getString("username"));
user.setPassword(resultSet.getString("password"));
user.setNickname(resultSet.getString("nickname"));
list.add(user);
}
//7、释放资源,归还连接给连接池
JdbcUtils.closeAll(resultSet,preparedStatement,null);
myDataSource.addBack(connection);
//8、集合处理,(1)返回return (2)打印输出了
for(User user:list){
System.out.println(user.toString());
}
}