JDBC简介和使用
java程序操作数据库的方式有很多种,下面列举一些市面上常用的方式:
从图片分析的知:
MyBatis MyBatisPlus 这两个所占的比重比较大。都是用于简化JDBC开发的
JDBC:(Java DataBase Connectivity),就是使用Java语言操作关系型数据库的一套API。
JDBC的本质:
- sun公司官方定义的一套操作所有关系型数据库
- 各个数据库厂商去实现这套接口,提供忽聚酷驱动jar包
- 我们使用这套接口(JDBC)编程,真正执行的代码时驱动jar包中的实现类
快速入门
- 1,创建项目,引入mysql的驱动,junit依赖
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.33</version></dependency>
- 2,注册驱动
Class.forName("com.mysql.cj.jdbc.Driver");
- 3,获取连接对象Connection
Connection connection = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/web", "root", "root@1234")
- 4,获取SQL语句自行对象statement
Statement statement = connection.createStatement();
- 5, 执行SQL语句:
statement.executeUpdate("update user set password = '1234567890' where id = 1");
- 6, 释放资源:
statement.close();connection.close();
1,创建maven项目,引入MySQL的驱动和junit单元测试的依赖
在工程下,右击然后点击new,选择Module
选择 New Module 然后根据自己情况完成右边的配置
创建好工程之后,添加依赖。
2,注册驱动
//注册驱动Class.forName("com.mysql.cj.jdbc.Driver");
3,获取连接对象Connection
// 获取连接对象Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/sde01","root","root");
4,获取SQL语句自行对象statement
// 获取执行SQL的对象
Statement statement = connection.createStatement();
5, 执行SQL语句:
//执行SQL
statement.executeUpdate("update user set password = '666666' where id = 1");
6, 释放资源:
statement.close();connection.close();
完整操作:
这个数据库是我本地的sde01库中的user表
create table user(id int unsigned primary key auto_increment comment 'ID,主键',username varchar(20) comment '用户名',password varchar(32) comment '密码',name varchar(10) comment '姓名',age tinyint unsigned comment '年龄'
) comment '用户表';insert into user(id, username, password, name, age) values (1, 'daqiao', '123456', '大乔', 22),(2, 'xiaoqiao', '123456', '小乔', 18),(3, 'diaochan', '123456', '貂蝉', 24),(4, 'lvbu', '123456', '吕布', 28),(5, 'zhaoyun', '12345678', '赵云', 27);
我们在maven工程中,com.sde包下的子包 entity包创建一个User实体类
public class User {private Integer id;private String password;private String username;private String name;private Integer age;public User() {}public User(Integer id, String password, String username, String name, Integer age) {this.id = id;this.password = password;this.username = username;this.name = name;this.age = age;}@Overridepublic String toString() {return "User{" +"id=" + id +", password='" + password + '\'' +", username='" + username + '\'' +", name='" + name + '\'' +", age=" + age +'}';}
}
在创建一个测试类UpdateTest1:
@Testpublic void testJdbc() throws Exception {//注册驱动Class.forName("com.mysql.cj.jdbc.Driver");// 获取连接对象Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/sde01","root","root");//创建执行SQL的对象Statement statement = connection.createStatement();//返回影响的行数int rows = statement.executeUpdate("update user set password = '666666' where id = 1");System.out.println(rows > 0 ? "修改成功" : "修改失败");//关闭资源statement.close();connection.close();}
}
结果:
jdbc中的API详解
DriverManager
驱动管理器 ,注册驱动, 获取数据库连接 DriverManager.registerDriver(...)
注册驱动的步骤:
1,当类加载Driver驱动类时,会自动运行静态代码块中
2,Class.forName这步操作可以省略
SPI机制:Service Provider Interface,JDK内置的一种服务提供发现机制,可以轻松的扩展你得程序(切换实现),实现接口与实现类之间的解耦。
3 获取数据库连接:DriverManager.getConnection(url,user,password);
- url:数据库连接的url
- 语法:jdbc:mysql://ip地址(域名)/数据库名?参数键值对1&参数键值对2。
- 说明:如果连接的时是本机的默认端口的mysql,url可以简写为:jdbc:mysql:///数据库名?参数键值对...
user:用户名
password:数据库的密码
Connection
Connection的作用:获取执行SQL的对象
执行普通SQL对象Statement:connection.createStatement()执行预编译SQL对象PreparedStatement:connection.preparedStatement()
可以通过PreparedStatement解决SQL注入问题
- 获取PreparedStatement对象
- 设置参数值
- 执行SQL
@Testpublic void testLogin() throws Exception {Connection connection = PjdbcUtils.getConnection();String sql = "select * from user where username = ? and password = ?";PreparedStatement ps = connection.prepareStatement(sql);ps.setString(1,"xiaoqiao");ps.setString(2,"123456");ResultSet resultSet = ps.executeQuery();while (resultSet.next()){int id = resultSet.getInt("id");String username = resultSet.getString("username");String password = resultSet.getString("password");String name = resultSet.getString("name");int age = resultSet.getInt("age");User user = new User(id,username,password,name,age);System.out.println(user);}PjdbcUtils.close(connection,null,resultSet);}
效果:
Statement
statement的作用:执行SQL
- 执行DDL、DML语句:executeUpdate(sql); 如果是执行DML语句完毕,返回值int代表DML语句影响的函数。
- 执行SQL语句:executeQuery(sql); 返回值为ResultSet,里面封装了查询结果。
执行增删改executeUpdate() 会返回一个int类型的数据,表示影响的行数
执行查询时executeQuery() 会返回一个ResultSet的结果集
ResultSet
- ResultSet(结果对象集):封装了DQL查询语句查询的结果。
- next() 将光标从当前位置向前移动一行,并判断当前行是否是有效行,返回值为boolean
- getXxxx()获取数据:可以根据列的编号获取,也可以根据列名获取(推荐使用)
ResultSet rs = ps.executeQuery();while (rs.next()){int id = rs.getInt("id");String username = rs.getString("username");String password = rs.getString("password");String name = rs.getString("name");int age = rs.getInt("age");System.out.println(new User(id,username,password,name,age));}PjdbcUtils.close(connection,ps,rs);}
PreparedStatement
优势:
1,安全(防SQL注入)
2,性能高
1,获取PreparedStatement对象2,设置参数值 3,执行SQL
新建一个JDBC工具类,PjdbcUtils类
public class PjdbcUtils {public static final String URL = "jdbc:mysql://localhost:3306/sde01"; //改成你自己的数据库public static final String USER = "root"; //改成你自己的用户名public static final String PASSWORD = "root"; //改成你自己的密码public static Connection getConnection(){//加载驱动try {Class.forName("com.mysql.cj.jdbc.Driver");}catch (ClassNotFoundException e){e.printStackTrace();}//连接数据库Connection con = null;try {con = DriverManager.getConnection(URL,USER,PASSWORD);}catch (SQLException e){e.printStackTrace();}return con;}//关闭连接
public static void close(Connection con, Statement state, ResultSet rs) {if (rs != null) {try {rs.close();} catch (SQLException throwables) {throwables.printStackTrace();}}if (state != null) {try {state.close();} catch (SQLException throwables) {throwables.printStackTrace();}}if (con != null) {try {con.close();} catch (SQLException throwables) {throwables.printStackTrace();}}}}
使用JDBC完成增删改查的案例:
@DisplayName("使用PreparedStatement完成增删改查")
public class PselectTest {/*** 测试查询功能* @throws Exception*/@Test@DisplayName("测试查询功能")public void testLogin() throws Exception {Connection connection = PjdbcUtils.getConnection();String sql = "select * from user where username = ? and password = ?";PreparedStatement ps = connection.prepareStatement(sql);ps.setString(1,"xiaoqiao");ps.setString(2,"123456");ResultSet resultSet = ps.executeQuery();while (resultSet.next()){int id = resultSet.getInt("id");String username = resultSet.getString("username");String password = resultSet.getString("password");String name = resultSet.getString("name");int age = resultSet.getInt("age");User user = new User(id,username,password,name,age);System.out.println(user);}PjdbcUtils.close(connection,null,resultSet);}/*** 测试删除功能* @throws Exception*/@Test@DisplayName("测试删除功能")public void testDel() throws Exception {Connection connection = PjdbcUtils.getConnection();String sql = "delete * from user where id = ?";PreparedStatement ps = connection.prepareStatement(sql);ps.setInt(1,6);ps.executeUpdate();PjdbcUtils.close(connection,ps,null);}@Test@DisplayName("测试修改功能")public void testUpdate() throws Exception {Connection connection = PjdbcUtils.getConnection();String sql = "update user set username = ?,password = ?,name = ?,age = ? where id = ?";PreparedStatement ps = connection.prepareStatement(sql);ps.setString(1,"sundaoen");ps.setString(2,"121212");ps.setString(3,"戴恩");ps.setInt(4,18);ps.setInt(5,6);int rows = ps.executeUpdate();System.out.println(rows > 0 ? "修改成功" : "修改失败");PjdbcUtils.close(connection,ps,null);}@Test@DisplayName("测试新增功能")public void testAdd() throws Exception {Connection connection = PjdbcUtils.getConnection();String sql = "insert into user values(null,?,?,?,?)";PreparedStatement ps = connection.prepareStatement(sql);ps.setString(1,"luban");ps.setString(2,"666666");ps.setString(3,"鲁班");ps.setInt(4,13);int rows = ps.executeUpdate();System.out.println(rows > 0 ? "添加成功" : "添加失败");PjdbcUtils.close(connection,ps,null);}
}