连接数据库的方法更好?

时间:2018-01-10 22:10:19

标签: java jdbc

我的堆内存有问题。我的应用程序在Wildfly服务器上运行。我的一个应用程序使用类来创建与数据库的连接。

班级的结构是这样的。

public class Operations{
    private static Connection con;
    static Logger logger = Logger.getLogger(Operations.class);

    private static void setConnection() {


        try {

            con =DriverManager.getConnection("jdbc:sqlserver://server.domain.net:1111;databaseName=DATA","user","pass");//cap

        } catch (SQLException e) {
            e.printStackTrace();
            logger.debug(e.getLocalizedMessage());
        } 
    }

    public static Contract validateContract(String contractNumber) {
        logger.debug("Entre validad");
        try {
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
            logger.debug("Entre al metodo");
            setConnection();
            CallableStatement proc_stmt = con.prepareCall("{call database.storeProName(?)}");
            proc_stmt.setString(1, contractNumber);

            Contract contract = new Contract();
            ResultSet rs = proc_stmt.executeQuery();
            while (rs.next()) {
                contract.setValid(rs.getInt(1));
                contract.setContractID(rs.getInt(2));
                contract.setMessage(rs.getString(3));
            }

            return contract;
        } catch (Exception e) {
            Contract contmp = new Contract();
            contmp.setMessage(e.getMessage());
            contmp.setValid(0);
            return contmp;
        }
    }

.
.
.
public static Contract validateContract2(String contractNumber) {
        logger.debug("Entre validad");
        try {
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
            logger.debug("Entre al metodo");
            setConnection();
            CallableStatement proc_stmt = con.prepareCall("{call database.storeProName(?)}");
            proc_stmt.setString(1, contractNumber);

            Contract contract = new Contract();
            ResultSet rs = proc_stmt.executeQuery();
            while (rs.next()) {
                contract.setValid(rs.getInt(1));
                contract.setContractID(rs.getInt(2));
                contract.setMessage(rs.getString(3));
            }

            return contract;
        } catch (Exception e) {
            Contract contmp = new Contract();
            contmp.setMessage(e.getMessage());
            contmp.setValid(0);
            return contmp;
        }
    }
}

此类用于项目中的所有JSP。我不知道是否应该将代码更改为非静态类。我也应该关闭连接,但我不确定是否应关闭静态方法的连接。

0 个答案:

没有答案