2014-02-15 53 views
-1

我已經用盡了所有的途徑來解決這個問題,但無濟於事。我已經安裝了「SQL Management Studio 2012」並創建了一個虛擬數據庫和方法,但我仍然得到了「空點異常指針」。 Java和JDBC在用戶變量下設置。到數據庫的Java連接

下面是屏幕截圖和代碼。

Static { 
     // standard code to open a connection and statement to SQL Server database 
     try { 
      // Create a variable for the connection string. 
      String connectionUrl = "jdbc:sqlserver://SQL-SERVER;" 
        + "databaseName=ItunesDB;integratedSecurity=true;"; 

      // Establish the connection. 
      Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); 
      con = DriverManager.getConnection(connectionUrl); 

     } // Handle any errors that may have occurred. 
     catch (SQLException sqle) { 
      System.out.println("Sql Exception :" + sqle.getMessage()); 
     } catch (ClassNotFoundException e) { 
      System.out.println("Class Not Found Exception :" + e.getMessage()); 
     } 
    } 

    public static String listAll() { 
     String output = ""; 
     try { 
      stmt = con.createStatement(); 
      ResultSet res = stmt.executeQuery("SELECT * FROM LibraryTable"); 
      while (res.next()) { // there is a result 
       // the name field is the thrid one in the ResultSet 
       // Note that with ResultSet we count the fields starting from 1 
       output += res.getString(1) + " " + res.getString(2) + " - " 
         + res.getString(3) + " " + res.getString(4) + " " 
         + res.getString(5) + "\n"; 
      } 
     } catch (Exception e) { 
      System.out.println(e); 
      return null; 
     } 
     return output; 
    } 


public static String getName(String key) { 
     try { 

      SELECT * FROM LibraryTable WHERE key = '04'  
      stmt = con.createStatement(); 
      ResultSet res = stmt.executeQuery("SELECT * FROM LibraryTable WHERE ID = '" + key + "'"); 
      if (res.next()) { // there is a result 
       // the name field is the second one in the ResultSet 
       // Note that with ResultSet we count the fields starting from 1 
       return res.getString(2); 
      } else { 
       return null; 
      } 
     } catch (Exception e) { 
      System.out.println(e); 
      return null; 
     }`enter code here` 

數據庫信息:

Dummy Database 
ID Name Artist Quantity Price Rating Playcount 

什麼我需要做的,解決這一問題?

+0

其中u得到空指針異常? – Kick

+1

NPE在哪裏?堆棧跟蹤將會有所幫助。 – Makoto

+0

我的程序中的另一個類正在嘗試檢查磁道列表。顯然,在我的庫類中添加SQL代碼之前它正在工作。 – user3305841

回答

0

以混合模式重新安裝sql server。然後轉到SQL Server配置管理器並檢查是否啓用了TCP/Ip。如果不啓用它並重新啓動服務。然後在您的項目中添加sqljdbc jar。那就試試這個代碼

​​

用戶永遠是SA,因爲它是系統管理員

+0

非常感謝你,我會按照你的指示,並將返回一個反饋。 – user3305841