0

I have another class where a user a Book a resort, by only typing in the ID of the resort. Then a new JFrame opens(ConfirmBooking) where it displays the Name of the Resort and Price per night on labels. But I seem to be getting an error where I try to load the Resort name and price from the SQL database.

Error I get: Exception in thread "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);
        }
}
Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
Louw
  • 63
  • 10
  • 1
    Possible duplicate of [What is a NullPointerException, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – David May 17 '17 at 19:26
  • You never initialize the `conn` variable. Also, performing database operations (or any other complex I/O) in a constructor probably isn't the best idea. – David May 17 '17 at 19:27

1 Answers1

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);

You have to initialize your connection to Database

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