Separate JDBC Connection and ResultSet code

时间:2016-07-11 22:03:58

标签: java jdbc encapsulation

I want to separate my database connection code and my result set code. The only way that I can think of to do this is not ideal, because it would be creating 2 connection pools. Code snippet:

    public void connectivity() throws SQLException{

    try{
     Class.forName(driver);
     Connection c = DriverManager.getConnection(url, user, pass);
     Statement st = c.createStatement();
    }
   catch(ClassNotFoundException e){
    e.printStackTrace();
    }
   finally{
      try{
      c.close();

    }
     catch(Exception e){
     e.printStackTrace();
    }

   }
}

public Statement getStatement() throws SQLException{
         Class.forName(driver);
         Connection c = DriverManager.getConnection(url, user, pass);
         Statement st = c.createStatement();

         return st;

}

And then in another class I have:

Connectivity connect = new Connectivity();
Statement st = connect.getStatement();
ResultSet r = st.executeQuery(sql);

I do this because I need access to Statement in order to make the ResultSet work. How can I abstract the Connectivity code and the result set code to have them in 2 different modules, without having to create 2 connection pools?

Thanks in advance.

1 个答案:

答案 0 :(得分:0)

如果你想分离代码,你可能只想让连接成为一个成员变量,然后创建一个连接,然后创建语句或者实际创建另一个具有预准备语句的方法(另一个数据成员)然后只返回一个结果集。可能有很多方法可以做到这一点。这是一个让你走上正轨的例子:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class Connectivity {
    Connection connection;
    String url, user, pass, driver;

    public Connectivity(String url, String user, String pass, String driver) {
        super();
        this.url = url;
        this.user = user;
        this.pass = pass;
        this.driver = driver;
        try{
             Class.forName(driver);
             connection = DriverManager.getConnection(url, user, pass);

            }catch(ClassNotFoundException e){
                e.printStackTrace();
            } catch (SQLException e) {
                e.printStackTrace();
            }
    }

    public Statement getStatement() throws SQLException{
             return connection.createStatement();

    }

    public void close() throws SQLException{
        connection.close();
    }

    @Override
    protected void finalize() throws Throwable {
        super.finalize();
        connection.close();
    }
}

顺便说一句,可能有更好的方法来尝试做你想做的事情。您应该听EJP并查看Data Access Object Pattern