简体   繁体   中英

how do i resolve this java.lang.NullPointerException?

i am trying to run app that runs on both hsql and mysql database, to when i run it i get this error:

java.lang.NullPointerException: Cannot invoke "java.sql.Connection.prepareStatement(String)" because "this.cnn" is null
at DataBase.DBcontrol.creer_piece(DBcontrol.java:122)
at pdr.FrontController.initialize(FrontController.java:160)
at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2573)
at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2466)
at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3237)
at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3194)
at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3163)
at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3136)
at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3113)
at javafx.fxml/javafx.fxml.FXMLLoader.load(FXMLLoader.java:3106)
at pdr.Main.start(Main.java:13)
at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$9(LauncherImpl.java:846)
at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runAndWait$12(PlatformImpl.java:455)
at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$10(PlatformImpl.java:428)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:391)
at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$11(PlatformImpl.java:427)
at javafx.graphics/com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:96)
at javafx.graphics/com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at javafx.graphics/com.sun.glass.ui.win.WinApplication.lambda$runLoop$3(WinApplication.java:174)
at java.base/java.lang.Thread.run(Thread.java:832)

the chunck of code its reffering to in the first few lines are these:

  public void creer_piece() throws ClassNotFoundException {
                HConnexion dbc = new HConnexion();        cnn=dbc.connectDb();
    PreparedStatement pss;
    ResultSet s;
    try {
        req = "CREATE TABLE IF NOT EXISTS moussa.piece "
                + " (id VARCHAR(30), "
                + " atelier VARCHAR(30), "
                + " piece VARCHAR(30), "
                + " type VARCHAR(30) NULL, "
                + " pa VARCHAR(2) NULL, "
                + " ref1 VARCHAR(10) NULL , "
                + " ref2 VARCHAR(10) NULL  , "
                + " quant INTEGER,"
                + " emp VARCHAR(30),"
                + " pos VARCHAR(30),"
                +  " UNIQUE (id))";

        pss = cnn.prepareStatement(req);
        int e = pss.executeUpdate();
        if (e > 0) {
            JOptionPane.showMessageDialog(null, " erraurgg");
            
        }
    } catch (SQLException ex) {
        JOptionPane.showMessageDialog(null, ex);
    }

and this one:

 public void initialize(URL url, ResourceBundle rb) {
 
    try {
       run_wamp(); 
             timer.schedule(new TimerTask() {

            @Override
            public void run() {
               
            }
        },10000); 
        dbc.creer_piece();dbc.creer_refs();dbc.creer_carte();dbc.creer_module();dbc.creer_eqip();
         dbc.creer_c8();dbc.creer_secteur();dbc.creer_unite();dbc.creer_eqip();
        dbc.creer_atelier();
        dbc.get_natelier("SELECT * FROM moussa.atelier",combo_piece1);
    } catch (Exception ex) {
        Logger.getLogger(FrontController.class.getName()).log(Level.SEVERE, null, ex);
    }

i think it has to do with my database, either the app is not creating the tables or i should create the tables manually and connect them, though i am just spit balling here, need some help please.

edit: so after looking at the comments, you guys told me that cnn is returning null because of the connectDB well here it is:

    public class HConnexion {
     private static String msg ;
    Connection conn = null;Statement stm =null;
//=====================================================================================    
    public Connection connectDb() throws ClassNotFoundException {
        String s = System.getProperty("user.home");
        String JDBC_URL = "jdbc:hsqldb:Pdr_db;";
        run_wamp();
        String path= "jdbc:mysql://localhost:3306/mysql?zeroDateTimeBehavior=convertToNull";

        try {
           Class.forName("com.mysql.jdbc.Driver");
         Connection conn = DriverManager.getConnection(JDBC_URL, "root", ""); //hsql database
            conn = DriverManager.getConnection(path, "root", ""); //mysql database
           stm=conn.createStatement();
           stm.executeUpdate("create database IF NOT EXISTS moussa ");
            return conn;
        } catch (SQLException e) {
          
            JOptionPane.showMessageDialog(null, e);

            return null;
        }
    }

this method (correct me if i am wrong) is supposed to connect me to my database (or create a new one in case there isn't any), so if cnn is returning null, does that mean that its not creating a database which the other methods can connect through cnn.

The null pointer exception is caused by your incorrect connection code which returns null.

// code for HSQLDB
public class HConnexion {
private static String msg = "Cannot connect";
Connection conn = null;Statement stm =null;

public Connection connectDb() throws ClassNotFoundException, SQLException {
    String s = System.getProperty("user.home");
    String JDBC_URL = "jdbc:hsqldb:Pdr_db;"; // this is a HSQLDB URL
    run_wamp();
    // String path= "jdbc:mysql://localhost:3306/mysql?zeroDateTimeBehavior=convertToNull"; // we leave this out as you can connect only to one database, not two 

    try {
       Class.forName("org.hsqldb.jdbc.JDBCDriver");
       // Class.forName("com.mysql.jdbc.Driver");
       conn = DriverManager.getConnection(JDBC_URL, "root", ""); //hsql database - used
       // conn = DriverManager.getConnection(path, "root", ""); //mysql database - unused
       stm=conn.createStatement();
       // stm.executeUpdate("create database IF NOT EXISTS moussa "); // only for mysql
        return conn;
    } catch (SQLException e) {
      
        JOptionPane.showMessageDialog(msg, e);

        throw e;
    }
}

If you want to connect to MySQL, use this code

// code for MySQL
public class HConnexion {
private static String msg = "Cannot connect";
Connection conn = null;Statement stm =null;

public Connection connectDb() throws ClassNotFoundException, SQLException {
    String s = System.getProperty("user.home");
    // String JDBC_URL = "jdbc:hsqldb:Pdr_db;"; // this is a HSQLDB URL
    run_wamp();
    String path= "jdbc:mysql://localhost:3306/mysql?zeroDateTimeBehavior=convertToNull"; // we use this for MySQL

    try {
       // Class.forName("org.hsqldb.jdbc.JDBCDriver");
       Class.forName("com.mysql.jdbc.Driver");
       // conn = DriverManager.getConnection(JDBC_URL, "root", ""); //hsql database - unused
       conn = DriverManager.getConnection(path, "root", ""); //mysql database - used
       stm=conn.createStatement();
       stm.executeUpdate("create database IF NOT EXISTS moussa "); // only for mysql
       return conn;
    } catch (SQLException e) {
      
        JOptionPane.showMessageDialog(msg, e);

        throw e;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM