当前位置:Gxlcms > 数据库问题 > JDBC封装

JDBC封装

时间:2021-07-01 10:21:17 帮助过:20人阅读

//JDBC的封装
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
public class DBUtil {
    private static String url=null;
    private static String user=null;
    private static String password=null;
    static {
        Properties properties = new Properties();
        try {
            properties.load(DBUtil.class.getClassLoader().getResourceAsStream("dbconfig.properties"));
             String driver = properties.getProperty("driver");
             url = properties.getProperty("url");
             user = properties.getProperty("user");
             password = properties.getProperty("password");
             Class.forName(driver);
        
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {   
            e.printStackTrace();
        }
    }
    public static Connection getConn() {
        Connection conn =null;
        try {
            conn = DriverManager.getConnection(url, user, password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }
    public static void close(ResultSet rs,Statement stm,Connection conn) {
        if(rs!=null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(stm!=null) {
            try {
                stm.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(conn!=null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

//dbconfig.properties 配置文件

driver =com.mysql.jdbc.Driver
url =jdbc:mysql://localhost:3306/javaee1906
user=root
password=123789

JDBC封装

标签:ade   oca   void   man   loader   for   resultset   name   com   

人气教程排行