前言
本文介绍的JDBC,即Java Database Connectivity,java数据库连接。是一种用于执行SQL语句的Java API,它是Java中的数据库连接规范。这个API由 java.sql.,javax.sql. 包中的一些类和接口组成,可以为多种关系数据库提供统一访问,它由一组用Java语言编写的类和接口组成。
??博客主页: ??【】??
??精品Java专栏【JavaSE】、【备战蓝桥】[、【JavaEE初阶】](https://blog.youkuaiyun.com/qq_60856在这里插入图片描述
948/category_11797340.html)、【MySQL】、【数据结构】
??欢迎点赞 ?? 收藏 留言评论 ??私信必回哟????本文由 【】 原创,首发于 优快云??
??博主将持续更新学习记录收获,友友们有任何问题可以在评论区留言
??内容导读??
MySQL JDBC编程
??1.准备工作
1.1 下载驱动包
下载链接:maven中央仓库
第一步,点进网址进入maven中央仓库。
第二步,搜索MySQL,选择如下图大红框内位置。
第三步,根据自己的MySQL版本下载对应系列的jar包(大版本匹配即可,比如我的是5.7那么下载5系列的都可以)
第四步,点击下载即可
下载好以后放在自己可以找到的地方,然后开始导包。
1.2 导包
在完成一个项目需要使用到JDBC技术时,需要先在项目中完成jar包的导入,才能获取到各种数据库统一适配的接口,进一步完成JDBC编程。
第一步,在src的同级目录下创建目录(文件名自定,此处我用的是lib,用于存放jar包)
第二步,将第一步已经下载好的jar包复制,然后粘贴到创建的目录下
第三步,Add as Library
至此,我们就已经完成了JDBC编程的所有准备工作。
??2.使用步骤
2.1 创建数据源连接Connection
-
一种是利用DataSource(数据源对象获取)
//先获取数据源
DataSource dataSource = new MysqlDataSource();//再将MysqlDataSource向上转型,完成URL、User、Password的设置
((MysqlDataSource) dataSource).setUrl(“jdbc:mysql://localhost:3306/test?characterEncoding=utf8&useSSL=false”);//test处可替换 此处为所需要连接的数据库名
((MysqlDataSource) dataSource).setUser(“root”);//本地mysql客户端用户名
((MysqlDataSource) dataSource).setPassword(“1234”);//本地mysql客户端密码//完成连接
Connection connection = dataSource.getConnection(); -
另一种是通过是DriverManager(驱动管理类)的静态方法获取:
// 加载JDBC驱动程序
Class.forName(“com.mysql.jdbc.Driver”);
// 创建数据库连接
Connection connection = DriverManager.getConnection(url);
但在实际开发中,更多的是用到第一种方式,这是因为第二种方式,一是涉及到了反射,反射本身就是一个不太安全的操作;二是因为DriverManger每次getConnection都需要重新连接,但DataSource内置连接池,资源可以反复利用,效率更高。
2.2 构造SQL语句
此次示例以插入操作为例来进行操作
表结构如下图:
拼装好sql语句后,需要创建PreparedStatement对象来完成SQL的组装,在SQL语句中的占位符,用statement.setXX(1,id)方法来完成替换,数字代表第几个占位符,后边的参数为对应实例。
// [用户输入] 通过用户输入的数据, 来确定插入的值.
Scanner scanner=new Scanner(System.in);
System.out.println("请输入要插入的学号:");
int id=scanner.nextInt();
System.out.println("请输入要插入的姓名:");
String name=scanner.next();
//构造要执行的SQL语句;使用?作为占位符,后边会完成替换
String sql="insert into student values(?,?)";
PreparedStatement statement=connection.prepareStatement(sql);
statement.setInt(1,id);
statement.setString(2,name);
2.3 执行SQL
int n=statement.executeUpdate();
System.out.println("n="+n);
执行 SQL [发送请求 & 读取响应]
执行方法, 有两个
executeUpdate 对应插入删除修改语句. 返回值表示这次 SQL 操作影响到的行数.
executeQuery 对应查询语句. 返回值则是返回的临时表数据.
2.3 关闭释放资源
在完成SQL语句的执行后,及时关闭释放资源,防止资源泄漏
statement.close();
connection.close();
??3.开发案例
3.1 insert示例(插入示例)
public class JDBCInsert {
// 通过 JDBC 来操作数据库, 往数据库里插入一条记录.
// 往 test 这个数据库中的 student 表里, 插入一条记录.
public static void main(String[] args) throws SQLException {
// 1. 创建数据源对象. 数据源对象就描述了要访问的数据库是啥, 在哪.
DataSource dataSource = new MysqlDataSource();
((MysqlDataSource)dataSource).setURL("jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf8&useSSL=false");
((MysqlDataSource)dataSource).setUser("root");
((MysqlDataSource)dataSource).setPassword("1234");
// 2. 让代码和数据库服务器建立连接.
Connection connection = dataSource.getConnection();
// System.out.println(connection);
// [用户输入] 通过用户输入的数据, 来确定插入的值.
Scanner scanner = new Scanner(System.in);
System.out.println("请输入要插入的学号: ");
int id = scanner.nextInt();
System.out.println("请输入要插入的姓名: ");
String name = scanner.next();
// 3. 构造要执行的 SQL 语句~~ [构造请求]
// 使用 ? 作为占位符. 占个位置, 后面会替换成其他的值.
String sql = "insert into student values(?, ?)";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setInt(1, id);
statement.setString(2, name);
System.out.println("statement: " + statement);
// 4. 执行 SQL [发送请求 & 读取响应]
// 执行方法, 有两个
// executeUpdate 对应插入删除修改语句. 返回值表示这次 SQL 操作影响到的行数.
// executeQuery 对应查询语句. 返回值则是返回的临时表数据.
int n = statement.executeUpdate();
System.out.println("n = " + n);
// 5. 完成之后, 就需要关闭释放相关资源.
statement.close();
connection.close();
}
}
3.2 delete示例(删除示例)
public class JDBCDelete {
public static void main(String[] args) throws SQLException {
//1.创建数据源
DataSource dataSource = new MysqlDataSource();
((MysqlDataSource)dataSource).setURL("jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf8&useSSL=false");
((MysqlDataSource)dataSource).setUser("root");
((MysqlDataSource)dataSource).setPassword("1234");
//2.和数据库建立连接
Connection connection=dataSource.getConnection();
//3.构造SQL语句
Scanner scanner=new Scanner(System.in);
System.out.println("请输入要删除的学号:");
int id=scanner.nextInt();
String sql="delete from student where id=?";
PreparedStatement statement=connection.prepareStatement(sql);
statement.setInt(1,id);
//4.执行SQL
int n=statement.executeUpdate();
System.out.println("n=:"+n);
//5.释放资源
statement.close();
connection.close();
}
}
3.3 update示例(修改示例)
public class JDBCUpdate {
public static void main(String[] args) throws SQLException {
//1.创建数据源
DataSource dataSource = new MysqlDataSource();
((MysqlDataSource)dataSource).setURL("jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf8&useSSL=false");
((MysqlDataSource)dataSource).setUser("root");
((MysqlDataSource)dataSource).setPassword("1234");
//2.和数据库建立连接
Connection connection=dataSource.getConnection();
//3.构造SQL语句
Scanner scanner=new Scanner(System.in);
System.out.println("请输入要修改的同学学号:");
int id=scanner.nextInt();
System.out.println("请输入要修改的同学姓名: ");
String name = scanner.next();
String sql = "update student set name = ? where id = ?";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setString(1, name);
statement.setInt(2, id);
// 4. 执行 SQL
int n = statement.executeUpdate();
System.out.println("n = " + n);
// 5. 关闭释放资源
statement.close();
connection.close();
}
}
3.4 select示例(查找示例)
查询语句要使用 executeQuery 来完成
返回的结果是 ResultSet . 结果集.里面是一个 “表” 这样的数据结构.
一个表里有很多行, 每一行有很多列。
public class JDBCSelect {
public static void main(String[] args) throws SQLException {
// 1. 创建数据源
DataSource dataSource = new MysqlDataSource();
((MysqlDataSource)dataSource).setURL("jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf8&useSSL=false");
((MysqlDataSource)dataSource).setUser("root");
((MysqlDataSource)dataSource).setPassword("1234");
// 2. 建立连接
Connection connection = dataSource.getConnection();
// 3. 构造 SQL
String sql = "select * from student where id = ?";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setInt(1, 1);
// 4. 执行 SQL
ResultSet resultSet = statement.executeQuery();
// 5. 遍历结果集合
while (resultSet.next()) {
// 每次循环, 就能够获取到 resultSet 中的一行. 进一步的就可以拿到每一列!!
// getXXX 也是有一系列方法的. 会根据要取的数据的类型, 来灵活决策.
int id = resultSet.getInt(1);
String name = resultSet.getString(2);
System.out.println("id = " + id + ", name =" + name);
}
// 6. 释放资源
resultSet.close();
statement.close();
connection.close();
}
}
3.5 实际开发示例
我们可以发现,在3.1到3.4中,有很多冗余的代码,在实际开发中,这样肯定是很低效的,所以我们通常会把代码重复度高的部分抽象集中成方法,来减少代码的重复。
在上边的四个增删改查的示例中,其实除了sql语句的不同,其他都基本相同,首先我们可以把连接数据库方法和数据库关闭方法提取出来,如下:
public class MysqlUtil {
private static Connection connection;
private static PreparedStatement statement;
private static ResultSet rs;
private static String url="jdbc:mysql://localhost:3306/homework?characterEncoding=utf8&useSSL=false";
private static String user="root";
private static String password="1234";
public static Connection getConnection() throws Exception{
DataSource dataSource=new MysqlDataSource();
((MysqlDataSource)dataSource).setURL(url);
((MysqlDataSource)dataSource).setUser(user);
((MysqlDataSource)dataSource).setPassword(password);
Connection connection= dataSource.getConnection();
return connection;
}
public static void close() throws SQLException {
if(rs!=null)
rs.close();
if(statement!=null)
statement.close();
if(connection!=null)
connection.close();
}
}
这样抽象出来的MysqlUtil类,在调用该类的getConnection()方法时,就可以完成数据库的连接,然后再进一步自行完成sql语句的拼装执行,最后,在调用该类的close()方法,完成资源的释放关闭。
最后的话
总结不易,希望uu们不要吝啬你们的??哟(^U^)ノ~YO!!如有问题,欢迎评论区批评指正??
最后
深知大多数初中级Java工程师,想要提升技能,往往是自己摸索成长或者是报班学习,但对于培训机构动则近万的学费,着实压力不小。自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!
因此收集整理了一份《Java开发全套学习资料》送给大家,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。
小编已加密:aHR0cHM6Ly9kb2NzLnFxLmNvbS9kb2MvRFVrVm9aSGxQZUVsTlkwUnc==出于安全原因,我们把网站通过base64编码了,大家可以通过base64解码把网址获取下来。