package mes.util; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import org.springframework.stereotype.Service; import org.springframework.web.context.ContextLoader; import org.springframework.web.context.WebApplicationContext; import com.mchange.v2.c3p0.ComboPooledDataSource; @Service public class JdbcUtil { private static ComboPooledDataSource dataSource; /* private static String driver = null; private static String url = null; private static String username = null; private static String password = null;*/ static{ try{ /* //获取数据库连接驱动 driver = Config.getString("database.driver"); //获取数据库连接URL地址 url = Config.getString("database.url"); //获取数据库连接用户名 username = Config.getString("database.username"); //获取数据库连接密码 password = Config.getString("database.password"); //测试代码 System.out.println("driver:"+driver); System.out.println("url:"+url); System.out.println("username:"+username); System.out.println("password:"+password); //加载数据库驱动 Class.forName(driver);*/ //Connection connection = util.dataSource.getConnection(); System.out.println("static init"); WebApplicationContext appContext = ContextLoader.getCurrentWebApplicationContext(); //WebApplicationContextUtils.getRequiredWebApplicationContext(ServletContext sc); //ApplicationContext appContext=new ClassPathXmlApplicationContext("/config/applicationContext.xml"); dataSource = (ComboPooledDataSource) appContext.getBean("dataSource"); }catch (Exception e) { throw new ExceptionInInitializerError(e); } } /** * @Description: 获取数据库连接对象 * @return Connection数据库连接对象 * @throws SQLException */ /* public static Connection getConnection() throws SQLException{ return DriverManager.getConnection(url, username,password); }*/ public static Connection getConnection(){ try { Connection connection = dataSource.getConnection(); return connection; } catch (SQLException e) { e.printStackTrace(); return null; } } /** * @Method: release * @Description: 释放资源, * 要释放的资源包括Connection数据库连接对象,负责执行SQL命令的Statement对象,存储查询结果的ResultSet对象 * @param conn * @param st * @param rs */ public static void release(Connection conn,Statement st,ResultSet rs){ if(rs!=null){ try{ //关闭存储查询结果的ResultSet对象 rs.close(); }catch (Exception e) { e.printStackTrace(); } rs = null; } if(st!=null){ try{ //关闭负责执行SQL命令的Statement对象 st.close(); }catch (Exception e) { e.printStackTrace(); } } if(conn!=null){ try{ //关闭Connection数据库连接对象 conn.close(); }catch (Exception e) { e.printStackTrace(); } } } }
Jdbc.java工具类
猜你喜欢
转载自blog.csdn.net/zxf1242652895/article/details/80047685
今日推荐
周排行