准备和执行SQL语句等操作
发布时间:2025-06-24 19:34:30 作者:北方职教升学中心 阅读量:114
catch (SQLException e)
表示捕获 SQLException
异常。catch 块:
catch
块捕获在try
块中发生的异常。在你的代码中,finally
块用于关闭PreparedStatement
和Connection
对象,以防止资源泄漏。目录
前言
数据表的建立
操作包各个类的实现
增加类
删除类
展示类
借阅与归还类
前言
书接上文
JDBC编程的学习——MYsql版本-CSDN博客
本期我们通过对先前图书管理系统进行改造,是它的数据能保存在数据库中
完整代码我已经保存在github中,能不能给个星呢!!!!
calljsh/MyJava (github.com)
这是先前的图书管理系统,这篇博客里面也有完整代码
图书管理系统(java) 代码展示和思路介绍 (9000字小长文)_图书管理系统关键代码展示-CSDN博客
数据表的建立
即为简易图书管理系统,我只用了一张表来储存书的信息,包括书名,作者名,价格,类型,以及是否借出 的State.
这是我们表的结构
mysql> desc lib;+--------+-------------+------+-----+--------------+-------+| Field | Type | Null | Key | Default | Extra |+--------+-------------+------+-----+--------------+-------+| name | varchar(20) | YES | | NULL | || author | varchar(20) | YES | | NULL | || price | int | YES | | NULL | || type | varchar(20) | YES | | NULL | || state | varchar(20) | YES | | 未被借出 | |+--------+-------------+------+-----+--------------+-------+
具体创建的代码如下
create table lib (name varchar(20),author varchar(20),price int,type varchar(20),state varchar(20) default '未被借出');
我们给我们的状态列设置默认值——未被借出
好的现在我们的表建好了
操作包各个类的实现
整个图书管理系统的逻辑在之前的博客中已经详细介绍过,只要操作包中的各个类有区别,这也是我需要介绍的实例.
增加类
增加类就是写好我们需要增加书籍的信息,然后通过SQL语句使数据库执行
还是基础的五步,大致为:
创建数据源
建立链接
写好sql语句并执行
处理结果集
释放资源
package Operation;import Book.BOOK;import Book.BookList;import com.mysql.cj.jdbc.MysqlDataSource;import javax.sql.DataSource;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.SQLException;import java.util.Scanner;public class Add implements WORK{ @Override public void work(BookList bookList)throws SQLException { //1 创建 DataSource dataSource=new MysqlDataSource(); ((MysqlDataSource)dataSource).setURL("jdbc:mysql://127.0.0.1:3306/jsh?characterEncoding=utf8&useSSL=false"); ((MysqlDataSource)dataSource).setUser("root"); ((MysqlDataSource)dataSource).setPassword("你的密码"); //2 建立链接 Connection connection=dataSource.getConnection(); //3 创建sql语句 System.out.println("增加图书"); Scanner scanner=new Scanner(System.in); System.out.println("请输入您要添加的图书的书名:"); String name= scanner.nextLine(); System.out.println("请输入您要添加的图书的作者名:"); String author = scanner.nextLine(); System.out.println("请输入您要添加的图书的类型:"); String type = scanner.nextLine(); System.out.println("请输入您要添加的图书的价格:"); int price = scanner.nextInt(); String sql="insert into lib (name,author,price,type,state)values(?,?,?,?,default)"; PreparedStatement preparedStatement=connection.prepareStatement(sql); preparedStatement.setString(1,name); preparedStatement.setString(2,author); preparedStatement.setInt(3,price); preparedStatement.setString(4,type); //4 发送给服务器 int n=preparedStatement.executeUpdate(); //5 释放资源 preparedStatement.close(); connection.close(); }}
有一个要点需要注意,为了能够让状态(state)能够是我们设置好的默认值,我指定了列,如果有更好的写法欢迎分享
删除类
删除类其实和增加类是一样的,但是我用了try-catch-finally结构写给读者们看
try { // 建立连接 connection = dataSource.getConnection(); // 获取用户输入 Scanner sc = new Scanner(System.in); System.out.println("输入你要删除图书的名字:"); String name = sc.nextLine(); // 创建SQL语句 String sql = "DELETE FROM lib WHERE name = ?"; preparedStatement = connection.prepareStatement(sql); preparedStatement.setString(1, name); // 执行删除操作 int rowsAffected = preparedStatement.executeUpdate(); if (rowsAffected > 0) { System.out.println("图书删除成功"); } else { System.out.println("没有找到要删除的图书"); }} catch (SQLException e) { e.printStackTrace();} finally { // 关闭资源 if (preparedStatement != null) { try { preparedStatement.close(); } catch (SQLException e) { e.printStackTrace(); } } if (connection != null) { try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } }}
下面是大致的解释
try 块:
try
块中的代码是你希望正常执行的代码。在代码中,try
块包含建立数据库连接、if (connection != null) { connection.close(); }
关闭Connection
对象。
使用tyr-catch-finally结构去写,能够捕获到异常,也让代码更具"健壮性"
展示类
展示类中,我们就能看见结果集了,本质上来说,展示就是查询,然后打印出查询的结果
所以代码如下
package Operation;import Book.BOOK;import Book.BookList;import com.mysql.cj.jdbc.MysqlDataSource;import javax.sql.DataSource;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.util.Scanner;public class Show implements WORK{ @Override public void work(BookList bookList) throws SQLException { // 1 创建 DataSource dataSource = new MysqlDataSource(); ((MysqlDataSource) dataSource).setURL("jdbc:mysql://127.0.0.1:3306/jsh?characterEncoding=utf8&useSSL=false"); ((MysqlDataSource) dataSource).setUser("root"); ((MysqlDataSource) dataSource).setPassword("454284665"); // 2 建立链接 Connection connection = dataSource.getConnection(); // 3 创建sql语句 String sql = "SELECT * FROM lib"; PreparedStatement preparedStatement = connection.prepareStatement(sql); // 4 发送给服务器并获取结果 ResultSet resultSet = preparedStatement.executeQuery(); // 5 处理结果 while (resultSet.next()) { String name = resultSet.getString("name"); String author = resultSet.getString("author"); int price = resultSet.getInt("price"); String type = resultSet.getString("type"); String state=resultSet.getString("state"); System.out.println("书名: " + name + " 作者: " + author + " 价格: " + price + " 类型: " + type + " 状态: "+state); } // 6 释放资源 resultSet.close(); preparedStatement.close(); connection.close(); }}
结果集中它通过一套getXXX方法来获取数据,通过next()方法来读取给个查询的字段
我们通过这两种方法获得数据库的数据,然后打印出来
最后释放资源
借阅与归还类
借阅也是先通过查询,如果有查询的书,就把state修改为 '已借出' 即可
package Operation;import Book.BOOK;import Book.BookList;import com.mysql.cj.jdbc.MysqlDataSource;import javax.sql.DataSource;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.util.Scanner;public class Borrow implements WORK{ @Override public void work(BookList bookList) throws SQLException { DataSource dataSource=new MysqlDataSource(); ((MysqlDataSource)dataSource).setURL("jdbc:mysql://127.0.0.1:3306/jsh?characterEncoding=utf8&useSSL=false"); ((MysqlDataSource)dataSource).setUser("root"); ((MysqlDataSource)dataSource).setPassword("454284665"); //2 建立链接 Connection connection=dataSource.getConnection(); Scanner sc=new Scanner(System.in); System.out.println("请输入你要借的书的名字"); String name=sc.nextLine(); //3 String sql = "select * from lib where name= ?and state ='未被借出'"; PreparedStatement preparedStatement = connection.prepareStatement(sql); preparedStatement.setString(1, name); // 4 发送给服务器并获取结果 ResultSet resultSet = preparedStatement.executeQuery(); if(resultSet.next()) { String sql1="update lib set state ='已借出' where name=?"; PreparedStatement preparedStatement1=connection.prepareStatement(sql1); preparedStatement1.setString(1,name); int n= preparedStatement1.executeUpdate(); if(n>0) { System.out.println("借阅成功"); preparedStatement1.close(); } } else { System.out.println("没有找到这本书,借阅失败"); } //5 释放资源 resultSet.close(); preparedStatement.close(); connection.close();
归还和借阅正好相反,这里我同样用try-catch-finally结构去写
package Operation;import Book.BOOK;import Book.BookList;import com.mysql.cj.jdbc.MysqlDataSource;import javax.sql.DataSource;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.util.Scanner;public class Return implements WORK{ @Override public void work(BookList bookList) { DataSource dataSource = new MysqlDataSource(); ((MysqlDataSource) dataSource).setURL("jdbc:mysql://127.0.0.1:3306/jsh?characterEncoding=utf8&useSSL=false"); ((MysqlDataSource) dataSource).setUser("root"); ((MysqlDataSource) dataSource).setPassword("454284665"); Connection connection = null; PreparedStatement preparedStatement = null; PreparedStatement preparedStatement1 = null; ResultSet resultSet = null; try { connection = dataSource.getConnection(); Scanner sc = new Scanner(System.in); System.out.println("请输入你要归还的书的名字:"); String name = sc.nextLine(); String sql = "SELECT * FROM lib WHERE name = ? AND state = '已借出'"; preparedStatement = connection.prepareStatement(sql); preparedStatement.setString(1, name); resultSet = preparedStatement.executeQuery(); if (resultSet.next()) { String sql1 = "UPDATE lib SET state = '未被借出' WHERE name = ?"; preparedStatement1 = connection.prepareStatement(sql1); preparedStatement1.setString(1, name); int n = preparedStatement1.executeUpdate(); if (n > 0) { System.out.println("归还成功"); } } else { System.out.println("没有找到这本书或这本书未被借出, 归还失败"); } } catch (SQLException e) { System.out.println("数据库操作失败: " + e.getMessage()); } finally { // 按正确顺序关闭资源 if (resultSet != null) { try { resultSet.close(); } catch (SQLException e) { e.printStackTrace(); } } if (preparedStatement != null) { try { preparedStatement.close(); } catch (SQLException e) { e.printStackTrace(); } } if (preparedStatement1 != null) { try { preparedStatement1.close(); } catch (SQLException e) { e.printStackTrace(); } } if (connection != null) { try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } }
这样我们就可以实现将数据写入数据库中,当然这是简易版本的,可以扩展的内容还有很多,例如可以建一张表存储用户的信息,可以建表存储已经借走的书等
就留给读者们自己去写了,这只是一个练习的实例
完整代码我已经分享
GitHub - calljsh/Mylibrary
connection = dataSource.getConnection();
尝试建立与数据库的连接。preparedStatement = connection.prepareStatement(sql);
准备SQL语句。
finally 块:
finally
块中的代码无论是否发生异常都会执行,通常用于清理资源。获取用户输入、preparedStatement.executeUpdate();
执行SQL语句。e.printStackTrace();
打印异常的堆栈跟踪信息,帮助我们了解错误发生的具体位置和原因。在代码中,捕获的异常类型是SQLException
,这是处理SQL操作时可能抛出的异常类型。准备和执行SQL语句等操作。if (preparedStatement != null) { preparedStatement.close(); }
关闭PreparedStatement
对象。