java JDBC 中的空指针异常
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25260029/
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
Null Pointer Exception in JDBC
提问by adrian
I'm trying to execute a Java file, but when I do I get an error NullPointerException
in this part of the program.
我正在尝试执行 Java 文件,但是当我执行NullPointerException
此操作时,程序的这一部分出现错误。
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.DriverManager;
import java.sql.SQLException;
public class HiveClient {
// JDBC driver required for Hive connections
private static String driverName = "org.apache.hadoop.hive.jdbc.HiveDriver";
private static Connection con;
private static Connection getConnection(String ip, String port, String user, String password) {
try {
// dynamically load the Hive JDBC driver
Class.forName(driverName);
} catch (ClassNotFoundException e) {
System.out.println(e.getMessage());
return null;
} // try catch
try {
// return a connection based on the Hive JDBC driver
return DriverManager.getConnection("jdbc:hive://" + ip + ":" + port + "/default?user=" + user + "&password=" + password);
} catch (SQLException e) {
System.out.println(e.getMessage());
return null;
} // try catch
} // getConnection
public static void main(String[] args) {
try {
// from here on, everything is SQL!
con = getConnection("130.206.80.46", "10000", "myuser", "mypasswd");
Statement stmt = con.createStatement();
ResultSet res = stmt.executeQuery("select column1,column2,otherColumns " + "from mytable where column1='whatever' and columns2 like '%whatever%'");
// iterate on the result
while (res.next()) {
String column1 = res.getString(1);
Integer column2 = res.getInt(2);
// whatever you want to do with this row, here
} // while
// close everything
res.close();
stmt.close();
con.close();
} catch (SQLException ex) {
System.exit(0);
} // try catch
}
// doQuery
} // HiveClient
This is the message:
这是消息:
Exception in thread "main" java.lang.NullPointerException
at HiveClient.main(HiveClient.java:34)
Java Result: 1
The line the exception is at:
异常所在的行:
Statement stmt = con.createStatement();
I've checked the java.sql.Connection
package and createStatement()
is allowed in the Method Summary.
我已经检查了java.sql.Connection
包裹并且createStatement()
在方法摘要中被允许。
回答by Stephen C
Let's apply some logicto the problem.
让我们对这个问题应用一些逻辑。
Q: Why is the NPE being thrown by that statement?
问:为什么该语句会抛出 NPE?
A: The only possible explanation is that con
has the value null
.
A: 唯一可能的解释是con
有值null
。
Q: Why does con
have the value null
.
问:为什么con
有值null
。
A: The only explanation is that this statement is assigning null
to con
:
A: 唯一的解释是这个语句是赋值null
给con
:
con = getConnection("130.206.80.46", "10000", "myuser", "mypasswd");
And that means that getConnection
returns null
.
这意味着getConnection
返回null
.
Q: Why is getConnection
returning null
.
问:为什么getConnection
回来了null
。
A: Look at the code for that method. There two places where it explicitlyreturns null
. First is when Class.forName(driverName)
throws a ClassNotFoundException
. Second is when DriverManager.getConnection(...)
throws an SQLException
. In all other cases, it will return a non-null value. (Read the javadocs ...)
答:查看该方法的代码。有两个地方明确返回null
. 首先是Class.forName(driverName)
抛出一个ClassNotFoundException
. 其次是DriverManager.getConnection(...)
抛出SQLException
. 在所有其他情况下,它将返回一个非空值。(阅读 javadocs ...)
Q: So which is it?
问:那是哪个?
A: Look at the code! Note that in both places where null
is returned, you wrote a message to standard output. That message will answer your question!!
- 答:看代码!请注意,在null
返回的两个地方,您都向标准输出写入了一条消息。该消息将回答您的问题!!
The reason you are getting into trouble here is that you are catching exceptions too soon, and returning null
as a "remedy". It is that null
that is causing the ultimate problem.
您在这里遇到麻烦的原因是您过早地捕获异常,并null
作为“补救措施”返回。正是这null
导致了最终的问题。
The correctway to implement this is to change the declaration for getConnection
to say that it throws ClassNotFoundException
and SQLException
. Then remove the handlers for those exceptions in getConnection
and handle them in main
instead. And when you do handle them, make sure that you output (or log) the stack traces ... to make it easier to diagnose the real cause of your problems.
实现这一点的正确方法是更改声明 forgetConnection
说它抛出ClassNotFoundException
和SQLException
。然后删除这些异常的处理程序getConnection
并main
改为处理它们。当你处理它们时,确保你输出(或记录)堆栈跟踪......以便更容易地诊断问题的真正原因。
(To the authors of some of the other answers: Debugging should not be a matter of guessingwhat the problem is. You should look at the evidence, and draw logicalconclusions from that evidence. When the evidence points to multiplepossible causes, consider them all. Guesswork is at best a shortcut. At worst, it will cause you to waste lots of time pursuing "theories" that cannot possibly be true.)
(对于其他一些答案的作者:调试不应该是猜测问题所在。您应该查看证据,并从该证据中得出合乎逻辑的结论。当证据指向多个可能的原因时,请考虑它们全部。猜测充其量只是一条捷径。最糟糕的是,它会让你浪费大量时间去追求不可能为真的“理论” 。)
回答by ppuskar
First of all check if your driver is successfully loaded and registered, also check if driver is in your classpath. make it a habit to have a null check before using references like Connection.
首先检查您的驱动程序是否已成功加载和注册,还要检查驱动程序是否在您的类路径中。养成在使用像 Connection 这样的引用之前进行空检查的习惯。
回答by carlspring
Your getConnection()
method should never print out the exception and then return null
. It should simply throw an exception, if the driver cannot be found or (for some reason) be successfully loaded. Your code doesn't check at all if the result of getConnection()
is null
and this would lead to a NullPointerException
. What would make sense to check, would be to see if you have the respective JDBC driver on your classpath.
您的getConnection()
方法不应该打印出异常然后返回null
。如果找不到驱动程序或(由于某种原因)成功加载,它应该简单地抛出异常。您的代码根本不检查getConnection()
is的结果是否null
会导致NullPointerException
. 检查什么是有意义的,是查看您的类路径上是否有相应的 JDBC 驱动程序。
回答by Thusitha Thilina Dayaratne
try to get connection using this sway
尝试使用这种方式建立连接
DriverManager.getConnection("jdbc:hive://" + ip + ":" + port+ "/default", user, password);
回答by Nikolay Gromov
Just to point out what was helpful to me. I added and extra permition to onCreate method of my activity:
只是指出什么对我有帮助。我为我的活动的 onCreate 方法添加了额外的许可:
if (Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
回答by Prabhu MD
Go to the Database and make sure that first column of your SQLquery is not null. i had same issue because my first column of SQLquery was null in DB. so these exception may occur that first column in your SQLquery is null in DB, and dont try to add null column of DB in SQLquery. i hope this might helped you.
转到数据库并确保 SQLquery 的第一列不为空。我有同样的问题,因为我的第一列 SQLquery 在 DB 中为空。所以这些异常可能会发生在你的 SQLquery 中的第一列在 DB 中为空,并且不要尝试在 SQLquery 中添加 DB 的空列。我希望这可以帮助你。
Prabhu MD
帕布医学博士
回答by jorrin
Try something like:
尝试类似:
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql:// localhost:PORT/DBName", "mysql", "mysql");