JDBC工具类Utils
配置类jdbc.properties
driverName=com.mysql.cj.jdbc.Driverurl=jdbc:mysql://localhost:3306/test?serverTimezone=Asia/Shanghaiusername=rootpassword=123456
注意:test是我的数据库名
package com.chinasoft.client;import java.io.InputStream;import java.sql.*;import java.util.Properties;public class JdbcUtils { private static String driverName=null; private static String url=null; private static String username=null; private static String password=null; static{ try{//JdbcUtils.class.getClassLoader()获取类加载器//JdbcUtils.class.getClassLoader().getResourceAsStream获取该类下的资源// 注意jdbc.properties一定要是在src目录下 InputStream in = JdbcUtils.class.getClassLoader().getResourceAsStream("jdbc.properties"); Properties properties=new Properties(); properties.load(in);//现在整个jdbc.properties里面的数据都被读取出来了,存放在properties里面了 driverName = properties.getProperty("driverName"); url = properties.getProperty("url"); username = properties.getProperty("username"); password = properties.getProperty("password");// 1.驱动只需加载一次 Class.forName(driverName); } catch (Exception e) { e.printStackTrace(); } }// 获取连接 public static Connection getConnection() throws SQLException { return DriverManager.getConnection(url,username,password); }// 释放连接 public static void release(Connection conn, Statement st, ResultSet rs){ if (rs!=null){ try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } if (st!=null){ try { st.close(); } catch (SQLException e) { e.printStackTrace(); } } if (conn!=null){ try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } }}
编写测试类
package com.chinasoft.client;import java.sql.Connection;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;public class JdbcUtilsTest { public static void main(String[] args){ Connection connection = null; Statement statement=null; String sql; ResultSet resultSet=null; try { connection = JdbcUtils.getConnection();//获取数据库连接 statement = connection.createStatement();//获取SQL的执行对象 sql="select * from user"; resultSet = statement.executeQuery(sql);//获取查询结果集 } catch (SQLException e) { e.printStackTrace(); }finally { JdbcUtils.release(connection,statement,resultSet); } }}