我对使用 Java 的 DatatBases 有点陌生,我一直想知道我是否以正确的方式工作。在我的代码中,所有数据库接口(interface)都是在一个名为 DataAccess 的类中完成的,这是我的代码示例:
请注意,我在进入函数 isValidOperator()
之前打开了一个连接 (connBlng
)。
这是正确的工作方式还是应该在每次需要访问数据库时打开和关闭连接?
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;
}
最佳答案
JDBC plain 并不是一个非常易于使用的 API。也许你可以看看 Dalesbread https://github.com/Blackrush/Dalesbred这是一个轻量级 JDBC 包装器。以下是关于 JDBC 包装器的常见讨论:simple jdbc wrapper .
我不建议一直关闭数据库连接,您应该为此使用池。通常创建数据库连接的成本很高。
关于java - 从数据库更新/查询的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17964994/