2016-01-22 241 views
-3

我們試圖從數據庫表中顯示textarea中的信息。Java空指針異常

public void displayEmployees() 
{  
    String sqlDisplayQuery =""; 
    sqlDisplayQuery+= "Select * from JAVAUSER.Employee"; 
    System.out.println(sqlDisplayQuery); 

    Driver.sendDBCommand(sqlDisplayQuery); 

    try 
{ 
    while (dbResults.next()) 
    { 
     int employeeID= dbResults.getInt(1); 
     String employeeFName = dbResults.getString(2); 
     String employeeLName = dbResults.getString(3); 
     System.out.println("Employee " +employeeID + employeeFName + employeeLName); 
     txtaOutput.appendText("Employee" +employeeID + employeeFName + employeeLName);     
    } 

    } 
    catch (SQLException e) 
    { 
    System.out.println(e.toString()); 
    } 

    } 
    public static boolean isNumeric(String string) 
    { 
    try 
    { 
     double num = Double.parseDouble(string); 
    } 
    catch(NumberFormatException e) 
    { 
     return false; 
    } 
    return true; 
    } 


    public static void sendDBCommand(String sqlQuery) 
{ 
    String URL = "jdbc:oracle:thin:@localhost:1521:XE"; 
    String userID = "javauser"; 
    String userPASS = "javapass"; 
    OracleDataSource ds; 

    try 
    { 
     ds = new OracleDataSource(); 
     ds.setURL(URL); 
     dbConn= ds.getConnection(userID, userPASS); 
     commStmt = dbConn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); 
     dbResults= commStmt.executeQuery(sqlQuery); 
    } 
    catch (SQLException e) 
    { 
     System.out.println(e.toString()); 
    } 
} 

我們在try語句中的while循環中得到一個空指針異常。 SQL沒有任何錯誤。任何幫助,將不勝感激

+1

你在哪裏設置'dbResults'? – Coderchu

+0

這裏是我的sendDB命令方法 – hamstrdethwagon

+2

在設置值之前正在訪問'dbResults'。看看你的方法被調用的順序。 – Jason

回答

0

看起來像dbResults字段是Driver類的靜態 - 這可能會導致嚴重的問題與多線程,並沒有利用適當的面向對象 - 但這超出了我猜想的範圍。

望着循環:

int employeeID= dbResults.getInt(1); 

,這是好的十歲上下,即使getInt()不會拋出NPE,你可能要檢查值爲SQL NULL與ResultSet.wasNull()

String employeeFName = dbResults.getString(2); 
    String employeeLName = dbResults.getString(3); 

這些可以爲null,但不會拋出NPE。

System.out.println("Employee " +employeeID + employeeFName + employeeLName); 
    txtaOutput.appendText("Employee" +employeeID + employeeFName + employeeLName); 

在這裏,在這兩條線,你Concat的字符串可能爲空,所以這兩個是NullPointerException異常的潛在來源。我只是想知道你的堆棧跟蹤中是否有行號可以幫助識別確切的位置...?

如果你想檢查什麼可以/不能從SQL ResultSet返回null,請選擇this