1

我对使用 Java 中的 DatatBases 有点陌生,我一直想知道我是否以正确的方式工作。在我的代码中,所有 DB 接口都在一个名为 DataAccess 的类中完成,这是我的代码示例:

请注意,我connBlng在进入函数之前打开了一个连接 () isValidOperator()

这是正确的工作方式还是应该在每次需要访问数据库时打开和关闭连接?

if(da.StartBlngConnection() == null)
    return "ERROR"
DataAccess da = new DataAccess();
da.isValidOperator("123")       

//this is code from DataAccess Class
public Boolean isValidOperator(String dn) {
    System.out.println( npgReqID + " - " + LOG_TAG + "inside isValidOperator : " + dn);
    PreparedStatement prepStmt = null;
    ResultSet queryResult = null;
    try{
        prepStmt = connBlng.prepareStatement("select network_id, network_identifier from operators where network_identifier = ?"); 
        prepStmt.setString(1, dn);
        queryResult = prepStmt.executeQuery();
        if (queryResult.next()) {
            return true;
        }
    }catch(Exception e){
        System.out.println(npgReqID + " - "  + e);
        DBLog("", new Date(),"" , npgReqID , "" ,"" , MakeSureNotOutOfRange(GetStackTrace(e),4000), "" , "");
        return false;
    } finally{
        closeStatmentandRS(queryResult, PreparedStatement);
    }

    return false;
} 
4

1 回答 1

0

JDBC plain 不是一个很容易使用的 API。也许你可以看看 Dalesbread https://github.com/Blackrush/Dalesbred,它是一个轻量级的 JDBC 包装器。以下是关于 JDBC 包装器的共同讨论:simple jdbc wrapper

我不建议一直关闭数据库连接,您应该为此使用池。通常创建一个数据库连接是昂贵的。

于 2013-07-31T08:21:52.460 回答