前面我们了解了mysql的命令行编程,现在了解一下使用java语言来连接数据库进行编程,这种方式在实际开发中是主流方式。这里使用mysql5的版本。然后对这些代码进行封装。
数据库编程必备一些条件,比如编程语言,用什么语言来开发,这里就使用java。数据库使用mysql。二者之间还需要数据库驱动包。不同的数据库,对应不同的编程语言提供了不同的数据库驱动包,MySQL提供了Java的驱动包mysql-connector-java,需要基于Java操作MySQL即需要该驱动包。这个数据库驱动包需要去mysql官网下载。不同的版本对应不同的数据包。
mysql5.1.47数据库驱动包
https://pan.baidu.com/s/1-en3mb1NuWLpmQU0hbk0SQ?pwd=1111提取码:1111。
Java的数据库编程时JDBC,java数据库连接。是一种用于执行SQL语句的Java API,它是 Java中的数据库连接规范。这个API由 java.sql.*,javax.sql.* 包中的一些类和接口组成,它为Java开发人员操作数据库提供了一个标准的API,可以为多种关系数据库提供统一访问。
使用JDBC有他的优势:
(1)操作数据库完全面向抽象接口编程;
(2)开发数据库应用不用限定在特定数据库厂商的API;
(3)程序的可移植性大大增强。
在idea中创建一个项目,创建项目后,在项目根目录下创建一个lib文件夹,把下载的jar包复制到lib文件夹下。然后右键单击jar包,找到add as library后点击,弹出来的框点击OK即可。

完成后点击jar包,你会看到jar包中的接口和方法。
在连接之前,我们先在mysql中创建一张表,比如student表,这个表只包含id int,name varcahr(20)。
- create table student
- (
- id int,
- name varchar(20)
- );
接下来就开始连接数据库。创建一个java文件后在main方法中开始。要操作数据库,就要先连上数据库服务器,描述清除服务器的所在位置。在JDBC里面,连接数据库,就要使用DataSource这个类来描述数据库的位置。
- public static void main(String[] args) {
- DataSource dataSource = new MysqlDataSource();
- }

DataSource是一个接口,不能直接实例化,使用MysqlDataSource实现了这个接口。这个过程就是向上转型。这个类是来自于驱动包的,包导入正确,才能正常显示。要连接数据库,需要知道数据库服务器的url,用户和密码。对mysql来说,url格式如下:
- //MySQL数据连接的URL参数格式如下:
- jdbc:mysql://服务器地址:端口/数据库名?参数名=参数值
- public static void main(String[] args) throws SQLException {
- //1、要操作数据库,先要连接,描述服务器位置
- //使用dataSource 描述MySQL服务器的位置
- //DataSource是一个接口,不能直接实例化
- //这个接口来自驱动包
- //向上转型
- DataSource dataSource = new MysqlDataSource();
-
- //描述服务器位置 -- url
- //jdbc:mysql:// 协议名 这个网址jdbc连接mysql使用
- //127.0.0.1 IP地址,描述互联网上主机位置,使用字符串描述
- //3306 端口号 区分当前这个主机上的哪个程序
- //blog 数据库名
- //?后面的参数设置客户端连接服务器使用的字符集
- //characterEncoding 字符集
- //useSSL 是否加密
- ((MysqlDataSource) dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/blog?characterEncoding=utf8&useSSL=false");
-
- //用户名和密码
- ((MysqlDataSource) dataSource).setUser("你的用户名");
- ((MysqlDataSource) dataSource).setPassword("你的密码");
-
- //2、和数据库服务器建立连接
- //使用getConnection建立连接,使用java.sql的
- //SQLException 数据库编程中常见的异常,受查异常
- //连接失败的时候,会抛出异常
- Connection connection = dataSource.getConnection();
-
- //类似于这样的结果com.mysql.jdbc.JDBC4Connection@3eb07fd3 --> 连接成功
- //access denied 说明用户名/密码错误
- System.out.println(connection);
-
- //3、构造sql语句
-
- //4、断开连接,释放资源
- //在后面创建的要先断开
- connection.close();
- }

1、描述服务器位置。这个过程我们需要先进行向上转型,然后向下转型。这样做,得到的数据源是DataSource类型,是一个通用的类型,可以代指任何数据库。后面如果需要更换数据库,只需要很小的改动。注意url一定要小心输入,或者直接复制粘贴后修改成自己的数据库的位置。
2、和数据库服务器建立连接。在网络通信中,有两种连接方式:“有连接”和“无连接”。数据库使用有连接的方式,这样的好处就是先看看通信的链路是否畅通,但是要记着不同的连接一定要及时释放。
数据库连接有两种方式:
(1)通过DriverManager(驱动管理类)的静态方法获取
// 加载JDBC驱动程序
Class.forName("com.mysql.jdbc.Driver");
// 创建数据库连接 Connection connection = DriverManager.getConnection(url);
(2)通过DataSource(数据源)对象获取。实际应用中会使用DataSource对象
DataSource ds = new MysqlDataSource(); ((MysqlDataSource) ds).setUrl("jdbc:mysql://localhost:3306/test"); ((MysqlDataSource) ds).setUser("root"); ((MysqlDataSource) ds).setPassword("root"); Connection connection = ds.getConnection();
DriverManager类来获取的Connection连接,是无法重复利用的,每次使用完以后释放资源 时,通过connection.close()都是关闭物理连接。
DataSource提供连接池的支持。连接池在初始化时将创建一定数量的数据库连接,这些连接 是可以复用的,每次使用完数据库连接,释放资源调用connection.close()都是将 Conncetion连接对象回收。这种方式是最常用的。
使用dataSource的getConnection方法连接的时候,一定要导入正确的包,来自java.sql。同时alt+enter抛出异常。

3、构造sql语句,这个在后面说明。
4、断开连接,释放资源。使用close()方法。

上述sql语句执行了插入操作。注意不能重复插入(1,张三),自带了主键。
为了把sql语句发送到数据库中,JDBC提供了三种对象:
(1)Statement,执行不带参数的简单sql语句;
(2)PreparedStatement,执行带参数或不带参数的sql语句。sql语句会自动预编译在数据库系统,速度快于statement对象,最常用。
(3)CallableStatement,执行数据库存储过程的调用。
如果我们要在控制台进行输入,那么图片中的sql写法不是很好。实际开发中需要使用占位符?。

- public static void main(String[] args) throws SQLException {
-
- DataSource dataSource = new MysqlDataSource();
- ((MysqlDataSource) dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/blog?characterEncoding=utf8&useSSL=false");
- ((MysqlDataSource) dataSource).setUser("root");
- ((MysqlDataSource) dataSource).setPassword("123456");
-
- 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();
-
- String sql = "insert into student values(?, ?)";
- PreparedStatement statement = connection.prepareStatement(sql);
-
- statement.setInt(1, id);
- statement.setString(2, name);
-
- long num = statement.executeLargeUpdate();
- System.out.println(num);
-
- statement.close();
- connection.close();
- }
增删改都适用于这种语法和格式。
executeUpdate()方法返回值是一个整数,指示受影响的行数,通常用于update、insert、delete 语句。
查询的语法和格式于增删改不相同。

查询使用的方法是executeQuery() 方法执行后返回单个结果集的,通常用于select语句,它的结果返回的不是数值,而是ResultSet对象。
ResultSet对象被称为结果集,代表符合SQL语句条件的所有行,并且通过一套getXXX方法提供了对这些行中数据的访问。 ResultSet里的数据一行一行排列,每行有多个字段,并且有一个记录指针,指针所指的数据行叫做当前数据行,我们只能来操作当前的数据行。我们如果想要取得某一条记录,就要使用ResultSet的next() 方法 ,如果我们想要得到ResultSet里的所有记录,就应该使用while循环。
新建一个Jdbc包,新建如下图的类。整个封装的结构如图。


使用的表是student(id int, name varchar(20))。
连接的需要一次就够了,所以把这个类变成一个静态类。
- package Jdbc;
-
- import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;
-
- import javax.sql.DataSource;
- import java.sql.*;
-
- /**
- * @author: Naion
- * @create: 2022-07-18 11:11
- * @Description:
- **/
-
- //这个类本质上是一个静态类,不需要实例化
- public class Util {
-
- //静态不可变
- private static final DataSource dataSource = new MysqlDataSource();
-
- //静态代码块,不需要多次连接
- static {
- ((MysqlDataSource) dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/blog?characterEncoding=utf8&useSSL=false");
- ((MysqlDataSource) dataSource).setUser("你的用户名");
- ((MysqlDataSource) dataSource).setPassword("你的密码");
- }
-
- public static void main(String[] args) {
- System.out.println(getConnection());
- }
-
- //数据库连接
- public static Connection getConnection() {
- try {
- return dataSource.getConnection();
- } catch (SQLException e) {
- throw new RuntimeException("获取数据库连接失败", e);
- }
- }
-
- //资源释放
- public static void close(Statement statement, Connection connection, ResultSet resultSet) {
- try {
- if (statement != null) {
- statement.close();
- }
- if (connection != null) {
- connection.close();
- }
- if (resultSet != null) {
- resultSet.close();
- }
- } catch (SQLException e) {
- throw new RuntimeException("数据库操作异常", e);
- }
- }
- }
- package Jdbc;
-
- import java.sql.Connection;
- import java.sql.PreparedStatement;
- import java.sql.SQLException;
- import java.util.Scanner;
-
- /**
- * @author: Naion
- * @create: 2022-07-18 11:23
- * @Description:
- **/
-
- public class Insert {
-
- public void insert() {
- Connection connection = null;
- PreparedStatement preparedStatement = null;
-
- try {
- connection = Util.getConnection();
- Scanner scanner = new Scanner(System.in);
- System.out.println("请输入新增的id");
- int id = scanner.nextInt();
- System.out.println("请输入新增的name");
- String name = scanner.next();
- String sql = "insert into student values(?, ?)";
- preparedStatement = connection.prepareStatement(sql);
-
- preparedStatement.setInt(1, id);
- preparedStatement.setString(2, name);
-
- int result = preparedStatement.executeUpdate();
- System.out.println("返回条数: " + result);
-
- } catch (SQLException e) {
- throw new RuntimeException("获取数据库连接失败", e);
- } finally {
- Util.close(preparedStatement, connection, null);
- }
- }
- }
- package Jdbc;
-
- import java.sql.Connection;
- import java.sql.PreparedStatement;
- import java.sql.SQLException;
- import java.util.Scanner;
-
- /**
- * @author: Naion
- * @create: 2022-07-18 15:16
- * @Description:
- **/
-
- public class Delete {
-
- public void delete() {
- Connection connection = null;
- PreparedStatement preparedStatement = null;
-
- try {
- connection = Util.getConnection();
- Scanner scanner = new Scanner(System.in);
- System.out.println("请输入删除的id");
- int id = scanner.nextInt();
- String sql = "delete from student where id = ?";
- preparedStatement = connection.prepareStatement(sql);
- preparedStatement.setInt(1, id);
-
- int result = preparedStatement.executeUpdate();
- System.out.println("返回条数: " + result);
-
- } catch (SQLException e) {
- throw new RuntimeException("获取数据库连接失败", e);
- } finally {
- Util.close(preparedStatement, connection, null);
- }
- }
- }
- package Jdbc;
-
- import java.sql.Connection;
- import java.sql.PreparedStatement;
- import java.sql.SQLException;
- import java.util.Scanner;
-
- /**
- * @author: Naion
- * @create: 2022-07-18 11:52
- * @Description:
- **/
-
- public class Update {
-
- public void update() {
- Connection connection = null;
- PreparedStatement preparedStatement = null;
-
- try {
- connection = Util.getConnection();
- Scanner scanner = new Scanner(System.in);
- System.out.println("请输入要修改的id");
- int id = scanner.nextInt();
- System.out.println("请输入修改后的的name");
- String name = scanner.next();
- String sql = "update student set name = ? where id = ?";
- preparedStatement = connection.prepareStatement(sql);
-
- preparedStatement.setString(1, name);
- preparedStatement.setInt(2, id);
-
- int result = preparedStatement.executeUpdate();
- System.out.println("返回条数: " + result);
-
- } catch (SQLException e) {
- throw new RuntimeException("获取数据库连接失败", e);
- } finally {
- Util.close(preparedStatement, connection, null);
- }
- }
- }
- package Jdbc;
-
- import java.sql.Connection;
- import java.sql.PreparedStatement;
- import java.sql.ResultSet;
- import java.sql.SQLException;
-
- /**
- * @author: Naion
- * @create: 2022-07-18 12:04
- * @Description:
- **/
-
- public class Select {
-
- public void select() {
- Connection connection = null;
- PreparedStatement preparedStatement = null;
- ResultSet resultSet = null;
-
- try {
- connection = Util.getConnection();
- String sql = "select * from student";
- preparedStatement = connection.prepareStatement(sql);
- resultSet = preparedStatement.executeQuery();
- while (resultSet.next()) {
- int id = resultSet.getInt("id");
- String name = resultSet.getString("name");
- System.out.println("id: " + id + " name: " + name);
- }
-
- } catch (SQLException e) {
- throw new RuntimeException("获取数据库连接失败", e);
- } finally {
- Util.close(preparedStatement, connection, resultSet);
- }
- }
- }
- package Jdbc;
-
- /**
- * @author: Naion
- * @create: 2022-07-18 11:57
- * @Description:
- **/
-
- public class Jdbc {
-
- public void insert() {
- new Insert().insert();
- }
-
- public void update() {
- new Update().update();
- }
-
- public void select() {
- new Select().select();
- }
-
- public void delete() {
- new Delete().delete();
- }
- }
用的时候直接实例化Jdbc类来使用就可以了。这个封装还是简单的封装,使用的表也是比较简单的表。需要更加复杂的功能可以自己去修改补充。对功能进行封装也可以算是一个小项目了,整个过程,难就难在如何写出一个框架来,一旦写出来了框架,要做的就是补充及完善。