Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Managing pooling datasource in Java web app with singleton class, Tomcat, C3P0
- import java.beans.PropertyVetoException;
- import java.sql.*;
- import javax.sql.*;
- import javax.naming.*;
- import com.mchange.v2.c3p0.*;
- public class MyDataSource {
- private static MyDataSource mds = new MyDataSource();
- public static DataSource ds;
- private MyDataSource() {
- try {
- ds = getDataSource();
- } catch (NamingException e) {
- e.printStackTrace();
- }
- }
- public static MyDataSource getInstance(){
- return mds;
- }
- public Connection getConnection() throws SQLException, NamingException {
- Connection myConnect = ds.getConnection();
- return myConnect;
- }
- private DataSource getDataSource() throws NamingException {
- ComboPooledDataSource cpds = new ComboPooledDataSource();
- try {
- cpds.setDriverClass( "com.mysql.jdbc.Driver" );
- } catch (PropertyVetoException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- cpds.setJdbcUrl( "jdbc:mysql://195.195.xx.xx:3306/dbName" );
- cpds.setUser("lemmy");
- cpds.setPassword("xxx");
- cpds.setMaxIdleTime(180);
- cpds.setMaxPoolSize(100);
- return cpds;
- }
- }
- import java.sql.*;
- import javax.sql.*;
- import javax.naming.*;
- public class DbConnection {
- public Connection c;
- public DbConnection() throws NamingException, SQLException {
- c = getConnection();
- }
- public Connection getConnection() throws SQLException, NamingException {
- Connection myConnect = MyDataSource.getInstance().getConnection();
- return myConnect;
- }
- public void close(){
- JDBCUtils.close(this.c);
- }
- }
- import java.sql.*;
- public class JDBCUtils {
- static public void close (ResultSet rs) {
- try { if (rs!=null) rs.close(); } catch (Exception e) {}
- }
- // Works for PreparedStatement also since it extends Statement.
- static public void close (Statement stmt) {
- try { if (stmt!=null) stmt.close(); } catch (Exception e) {}
- }
- static public void close (java.sql.Connection conn) {
- try { if (conn!=null) conn.close(); } catch (Exception e) {}
- }
- }
- String myQuery = null;
- DbConnection myConnect = null;
- Statement myStatement = null;
- ResultSet rs = null;
- try {
- myConnect = new DbConnection();
- myStatement = myConnect.c.createStatement();
- // Do stuff here
- }catch (SQLException e) {
- out.println("SQL Error: "+e);
- } finally {
- JDBCUtils.close(rs);
- JDBCUtils.close(myStatement);
- myConnect.close();
- }
Add Comment
Please, Sign In to add comment