为了以后方便进行数据库连接、数据库关闭、还有后面的连接池的操作等功能,现在将功能封装到JDBCUtils类当中,作为自己的一个工具箱。
package utils; import java.io.InputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Properties; import javax.sql.DataSource; import com.alibaba.druid.pool.DruidDataSourceFactory; /** * 操作数据库的工具类 * @author pc * */ 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); // 2. 读取配置信息 String user = pros.getProperty("user"); String password = pros.getProperty("password"); String url = pros.getProperty("url"); String driverClass = pros.getProperty("driverClass"); // 3. 加载驱动 Class.forName(driverClass); // 4. 获取连接 Connection conn = (Connection) DriverManager.getConnection(url, user, password); return conn; } /*** * 关闭连接和preparedStatement * @param conn * @param ps */ public static void closeResourse(Connection conn, PreparedStatement ps) { try { if(ps != null) ps.close(); } catch (SQLException e) { e.printStackTrace(); } try { if(conn != null) conn.close(); } catch (SQLException e) { e.printStackTrace(); } } /*** * 关闭连接、preparedStatement和ResultSet * @param conn * @param ps * @param rs */ public static void closeResourse(Connection conn, PreparedStatement ps, ResultSet rs) { try { if(ps != null) ps.close(); } catch (SQLException e) { e.printStackTrace(); } try { if(conn != null) conn.close(); } catch (SQLException e) { e.printStackTrace(); } try { if(rs != null) rs.close(); } catch (SQLException e) { e.printStackTrace(); } } /*** * * 使用Druid数据库连接池技术 */ private static DataSource source; static { try { Properties pros = new Properties(); InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("druid.properties"); pros.load(is); source = DruidDataSourceFactory.createDataSource(pros); } catch (Exception e) { e.printStackTrace(); } } public static Connection getConnectionDruid() throws Exception { Connection conn = source.getConnection(); return conn; } }