JavaJDBC-封装getConnection、closeResource方法
import org.apache.commons.dbutils.DbUtils; import java.io.InputStream; import java.sql.*; import java.util.Properties; /** * @author orz */ public class JDBCUtils { /** *创建数据库连接 * @return * @throws Exception */ public static Connection getConnection()throws Exception { //1.读取配置文件中四个基本信息 InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("jdbc.properties"); Properties pros=new Properties(); pros.load(is); String user=pros.getProperty("user"); String password=pros.getProperty("password"); String url=pros.getProperty("url"); String driverClass=pros.getProperty("driverClass"); //2.加载驱动 Class.forName(driverClass); //3.获取连接 Connection conn= DriverManager.getConnection(url,user,password); // System.out.println(conn); return conn; } /** *关闭资源Connection、PreparedStatement * @param conn * @param ps */ public static void closeResource(Connection conn, Statement ps) { try { if(conn!=null) { conn.close(); } } catch (SQLException e) { e.printStackTrace(); } try { if(ps!=null) { ps.close(); } } catch (SQLException e) { e.printStackTrace(); } } /** * 关闭资源Connection、PreparedStatement、ResultSet * @param conn * @param ps * @param rs */ public static void closeResource(Connection conn, Statement ps, ResultSet rs) { try { if(conn!=null) { conn.close(); } } catch (SQLException e) { e.printStackTrace(); } try { if(ps!=null) { ps.close(); } } catch (SQLException e) { e.printStackTrace(); } try { if(rs!=null) { rs.close(); } } catch (SQLException e) { e.printStackTrace(); } } //使用dbutils的jar包中提供的的DbUtils工具类,实现资源的关闭 public static void closeResource2(Connection conn, Statement ps, ResultSet rs) { DbUtils.closeQuietly(conn); DbUtils.closeQuietly(ps); DbUtils.closeQuietly(rs); } }