oracle DriverManager.getConnection() 返回 null,而不是连接对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5777735/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
DriverManager.getConnection() returns null, rather than a connection object
提问by Ross
I am trying to connect to an Oracle database via JDBC. Using the following code:
我正在尝试通过 JDBC 连接到 Oracle 数据库。使用以下代码:
Connection c = null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
c = DriverManager.getConnection(connURL, userID, password);
} catch (SQLException se) {
System.out.println(se.getMessage());
} catch (Exception e) {
System.out.println(e.getMessage());
}
For some reason no exception is thrown but c
remains null - what does this mean?
出于某种原因,没有抛出异常但c
仍为空 - 这是什么意思?
Update:
更新:
Turns out we were getting an exception - Class not found: "oracle.jdbc.driver.OracleDriver"
- we had the odbc classes outside the classpath.
结果我们得到了一个异常——Class not found: "oracle.jdbc.driver.OracleDriver"
我们在类路径之外有 odbc 类。
回答by Isaac Truett
This would have been easier to spot if you handled your exceptions differently. Just printing the exception message and moving on is rarely the right thing to do. What can you do when the database connection is null
? If you throw an exception indicating that the connection isn't available, then whatever routine is trying to get a connection to the database can alert the user to a potential system outage, log the error, and email a system administrator (for example). Just returning null
is less obvious to troubleshoot, as you have found.
如果您以不同的方式处理异常,这会更容易发现。只是打印异常消息并继续前进很少是正确的做法。数据库连接时你能做什么null
?如果您抛出一个异常表明连接不可用,那么任何试图连接到数据库的例程都可以警告用户潜在的系统中断、记录错误并向系统管理员发送电子邮件(例如)。正如null
您所发现的那样,仅返回就不太容易进行故障排除。