JDBC获取数据库连接的帮助类

 

import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Properties;

public class jdbcUtil {

    private static String driver;
    private static String url;
    private static String id;
    private static String password;

    //加载文件,获取配置参数
    static{
        Properties prop=new Properties();
        InputStream is;
        try {
            is = jdbcUtil.class.getClassLoader()
                .getResourceAsStream("com/sy/db/db.properties");
            prop.load(is);
            driver = prop.getProperty("driver");
            url = prop.getProperty("url");
            id = prop.getProperty("id");
            password = prop.getProperty("password");
        } catch (Exception e1) {
            e1.printStackTrace();
        }
    }

    //注册驱动
    static{
        try {
            Class.forName(driver);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //取得连接
    public static Connection getMysqlConnection(){
        Connection conn=null;
        try {
            conn=DriverManager.getConnection(url,id,password);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return conn;
    }

    //关闭流
    public static void close(ResultSet rs){
        if(null!=rs){
            try {
                rs.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    public static void close((Statement state){
        if(null!=rs){
            try {
                state.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    public static void close(Connection conn){
        if(null!=rs){
            try {
                conn.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-11-30
  • 2021-08-12
  • 2022-01-17
  • 2021-08-01
  • 2021-09-07
猜你喜欢
  • 2021-11-28
  • 2022-12-23
  • 2022-12-23
  • 2021-07-06
  • 2022-12-23
  • 2022-01-23
  • 2022-12-23
相关资源
相似解决方案