无法在标签上显示SQL数据

时间:2017-05-17 19:24:41

标签: java sql

我有另一个课程,用户只需输入度假村的ID即可预订度假村。然后打开一个新的JFrame(ConfirmBooking),在其中显示度假村的名称和标签上的每晚价格。但是我似乎在尝试从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 个答案:

答案 0 :(得分: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