2017-05-17 45 views
0

我有另一個類,其中用戶a通過輸入度假村的ID來預訂度假村。然後,打開一個新的JFrame(ConfirmBooking),在其中顯示標籤上每晚的度假村和價格的名稱。但是我似乎在嘗試從SQL數據庫加載度假村名稱和價格時出現錯誤。無法在標籤上顯示SQL數據

錯誤,我得到: 異常在線程 「AWT-EventQueue的-0」 顯示java.lang.NullPointerException

public class ConfirmBooking extends javax.swing.JFrame 

{ 

    Connection conn = null; 
    Statement stat = null; 
    ResultSet res = null; 
    Booking B = new Booking(); 



public ConfirmBooking() 
{ 
    initComponents(); 

    String sql = "SELECT RESORT_NAME, COST_PER_NIGHT_ZAR FROM LouwDataBase.Resorts WHERE ID = "+ 2; 
     try (PreparedStatement pstmt = conn.prepareStatement(sql)) 
     { 
       try (ResultSet rs = pstmt.executeQuery()) 
       { 
        if (rs.next()) 
        { 
        String Name = rs.getString("RESORT_NAME"); 
        double Price = rs.getDouble("COST_PER_NIGHT_ZAR"); 
        String Rands = Double.toString(Price); 
        ResortName.setText(Name); 
        ResortPrice.setText("R"+Rands); 
        } 
       } 
     } 
     catch (SQLException ex) 
     { 
      Logger.getLogger(Booking.class.getName()).log(Level.SEVERE, null, ex); 
     } 
} 
+1

您的連接可能的重複[什麼是NullPointerException,以及如何解決它?](http://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i -fix-it) – David

+0

你永遠不會初始化'conn'變量。另外,在構造函數中執行數據庫操作(或任何其他複雜的I/O)可能不是最好的主意。 – David

回答

0
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; 
    static final String DB_URL = "jdbc:mysql://localhost/EMP"; 

    // Database credentials 
    static final String USER = "username"; 
    static final String PASS = "password"; 

    public static void main(String[] args) { 
    Connection conn = null; 
    Statement stmt = null; 
    try{ 
     //STEP 2: Register JDBC driver 
     Class.forName("com.mysql.jdbc.Driver"); 

     //STEP 3: Open a connection 
     System.out.println("Connecting to database..."); 
     conn = DriverManager.getConnection(DB_URL,USER,PASS); 

你必須初始化數據庫

https://www.tutorialspoint.com/jdbc/jdbc-sample-code.htm