我正在尝试执行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
这是消息:
Exception in thread "main" java.lang.NullPointerException
at HiveClient.main(HiveClient.java:34)
Java Result: 1
例外行位于:
Statement stmt = con.createStatement();
我已经检查了java.sql.Connection
包装,并createStatement()
在“方法摘要”中允许使用。
让我们对问题应用一些逻辑。
问:为什么该声明会引发NPE?
答:唯一可能的解释是con
具有值null
。
问:为什么con
有价值null
。
答:唯一的解释是此语句分配null
给con
:
con = getConnection("130.206.80.46", "10000", "myuser", "mypasswd");
这意味着getConnection
回报null
。
问:为什么要getConnection
回来null
。
答:查看该方法的代码。它在两个地方显式返回null
。首先是什么时候Class.forName(driverName)
抛出一个ClassNotFoundException
。其次是何时DriverManager.getConnection(...)
抛出SQLException
。在所有其他情况下,它将返回非null值。(阅读javadocs ...)
问:那是什么?
答:看代码!请注意,在null
返回的两个地方,您都向标准输出写入了一条消息。该消息将回答您的问题!!
您在这里遇到麻烦的原因是,您太早捕获异常,并且null
作为“补救措施”返回。正是这null
导致了最终的问题。
实现此目的的正确方法是更改声明,getConnection
使其声明为引发ClassNotFoundException
和SQLException
。然后删除这些异常的处理程序getConnection
并main
改为处理它们。并且当您处理它们时,请确保您输出(或记录)堆栈跟踪信息...,以便更轻松地诊断出问题的真正原因。
(对于其他一些答案的作者:调试不应该只是猜测问题所在。您应该查看证据,并从该证据中得出合理的结论。当证据指向多种可能的原因时,请考虑这些问题。总而言之,猜测工作充其量是捷径。在最坏的情况下,它将导致您浪费大量时间去追求不可能成立的“理论” 。)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句