[英]Null Pointer Exception in JDBC
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()
。
Let's apply some logic to 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
. 答:唯一可能的解释是
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
: 答:唯一的解释是该语句为
con
分配了null
:
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 explicitly returns
null
. 它在两个地方显式返回
null
。 First is when Class.forName(driverName)
throws a ClassNotFoundException
. 首先是当
Class.forName(driverName)
抛出ClassNotFoundException
。 Second is when DriverManager.getConnection(...)
throws an SQLException
. 其次是当
DriverManager.getConnection(...)
抛出SQLException
。 In all other cases, it will return a non-null value. 在所有其他情况下,它将返回非空值。 (Read the javadocs ...)
(阅读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. 请注意,在两个都返回
null
地方,您都向标准输出写入了一条消息。 That message will answer your question!! 该消息将回答您的问题!
The reason you are getting into trouble here is that you are catching exceptions too soon, and returning null
as a "remedy". 您在这里遇到麻烦的原因是,您太早捕获到异常,并且返回
null
作为“补救措施”。 It is that null
that is causing the ultimate problem. 导致最终问题的是
null
。
The correct way to implement this is to change the declaration for getConnection
to say that it throws ClassNotFoundException
and SQLException
. 实现此目的的正确方法是更改
getConnection
的声明,使其声明它抛出ClassNotFoundException
和SQLException
。 Then remove the handlers for those exceptions in getConnection
and handle them in main
instead. 然后在
getConnection
删除这些异常的处理程序,而在main
处理它们。 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. 并且当您处理它们时,请确保输出(或记录)堆栈跟踪信息...,以便更轻松地诊断出问题的真正原因。
(To the authors of some of the other answers: Debugging should not be a matter of guessing what the problem is. You should look at the evidence, and draw logical conclusions from that evidence. When the evidence points to multiple possible 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 .) (对于其他一些答案的作者:调试不应该只是猜测问题所在。您应该查看证据,并从该证据中得出合理的结论。当证据指向多种可能的原因时,请考虑这些问题。总而言之,猜测工作最多是捷径。最坏的情况下,它将导致您浪费大量时间去追求不可能正确的 “理论”。)
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之类的引用之前,习惯进行null检查。
Your getConnection()
method should never print out the exception and then return null
. 您的
getConnection()
方法应该永远不要打印出异常,然后返回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
. 您的代码根本不会检查
getConnection()
的结果是否为null
,这将导致NullPointerException
。 What would make sense to check, would be to see if you have the respective JDBC driver on your classpath. 检查有意义的是查看类路径上是否有相应的JDBC驱动程序。
尝试使用此方式获得连接
DriverManager.getConnection("jdbc:hive://" + ip + ":" + port+ "/default", user, password);
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);
}
Go to the Database and make sure that first column of your SQLquery is not null. 转到数据库,并确保SQLquery的第一列不为空。 i had same issue because my first column of SQLquery was null in DB.
我有同样的问题,因为SQLquery的第一列在数据库中为空。 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.
因此,可能会发生以下异常:您的SQLquery中的第一列在DB中为null,并且不要尝试在SQLquery中添加DB的null列。 i hope this might helped you.
希望对您有帮助。
Prabhu MD 普拉布医学博士
Try something like: 尝试类似:
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql:// localhost:PORT/DBName", "mysql", "mysql");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.