JDBC之封装工具类(重用性方案)
JDBC之封装工具类(重用性方案)
实际JDBC使用过程中,存在大量重复代码,例如连接和数据库和关闭数据库
我们需要把传统JDBC代码重构,抽取JDBC工具类,以后连接数据库,释放资源,都可以使用这个工具类
工具类核心思想
封装获取连接,释放资源的两个方法
-
public static Connection getConnection(){}方法获取连接。
-
public static void closeAll(){}方法释放资源.
package com.qf.JDBC; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.Scanner; public class JDBC简化1 { public static void main(String[] args) throws Exception { Scanner scanner = new Scanner(System.in); System.out.println("请输入用户名:"); String username = scanner.nextLine();//next遇到空格结束,nextline能读取空格 System.out.println("请输入钱数:"); String money = scanner.nextLine(); //用工具类注册驱动,获得连接 Connection connection = DBUtils.getConnection(); //执行sql语句 //获得PreparedStatement对象,预编译Sql语句 PreparedStatement preparedStatement = connection.prepareStatement("select * from accounts where name =? and money=?;"); //每一个参数都有一个占位符?,在执行SQL语句之前,要给占位符赋值,占位符顺序从一开始 preparedStatement.setString(1,username); preparedStatement.setString(2,money); //执行sql语句,并接收结果 ResultSet resultSet = preparedStatement.executeQuery(); if(resultSet.next()){ System.out.println("登录成功!"); }else{ System.out.println("登录失败!"); } DBUtils.closeAll(connection,preparedStatement,resultSet); } }
工具类:
package com.qf.JDBC; import java.sql.*; public class DBUtils { static { try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { e.printStackTrace(); } } public static Connection getConnection(){ Connection connection = null; try { //加载驱动到虚拟机这一步没必要每次连接数据库都执行,写在静态代码块里,在类创建的时候就只执行一次 //Class.forName("com.mysql.jdbc.Driver"); String url = "jdbc:mysql://localhost:3306/jdbc?serverTimezone=UTC"; String name ="root"; String password = "123456"; connection = DriverManager.getConnection(url,name,password); } catch (SQLException e) { e.printStackTrace(); } return connection; } public static void closeAll(Connection connection, Statement statement, ResultSet resultSet){ try { if (resultSet!=null){ resultSet.close(); } if(statement!=null){ statement.close(); } if(connection!=null){ connection.close(); } } catch (SQLException e) { e.printStackTrace(); } } }
运行结果:
请输入用户名: A 请输入钱数: 1000 Loading class com.mysql.jdbc.Driver'. This is deprecated. The new driver class is
com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary. 登录成功!
Process finished with exit code 0