JDBC工具类_超基础_超easy

JdbcUtils—JDBC工具类

具体代码

import java.io.IOException;
import java.net.URL;
import java.sql.*;
import java.util.Properties;
​
public class JdbcUtils {
//url,user,password是 getConnection()函数的三个参数
    private static String url;
    private static String user;
    private static String password;
    private static String driver;
    //静态代码块
    static{
        Properties prop=new Properties();
        try {
            //获取src路径下文件的方式---ClassLoader类加载器
            ClassLoader classLoader = JdbcUtils.class.getClassLoader();
            URL resource = classLoader.getResource("jdbc.properties");
            String path = resource.getPath();
            prop.load(new FileReader("day01_jdbc\\src\\jdbc.properties"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        url=prop.getProperty("url");
        user=prop.getProperty("user");
        password=prop.getProperty("password");
        driver=prop.getProperty("driver");
        try {
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(url,user,password);
    }

     //释放资源
    public static void close(Statement stat, Connection conn){
        if(stat!=null){
            try {
                stat.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if(conn!=null){
            try {
                conn.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
    
    public static void close(ResultSet rs,Statement stat, Connection conn){
        if(rs!=null){
            try {
                rs.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if(stat!=null){
            try {
                stat.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if(conn!=null){
            try {
                conn.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
}

​配置文件

  • 放在src目录下
  • 文件名 jdbc.properties

文件内容

url=jdbc:mysql://localhost:3306/school?useSSL=false
user=用户名
password=密码
driver=com.mysql.jdbc.Driver

猜你喜欢

转载自blog.csdn.net/qq_45889221/article/details/107521941
今日推荐