I want to develop a JavaFX application that can store data in a database. But I'm getting a null pointer exception

时间:2018-09-18 20:27:59

标签: java postgresql javafx

This is a piece of my Database Class, what I want it to do is to get the String from the name Textfield in my Main Class and insert into the Database with the method insertIntoTable(). But all I get when I run the Application is Error in JavaFX Thread Null Pointer Exception.

this is my Application

Database Class:

    Connection connect() {
        Connection conn = null;
         try {
            Class.forName("org.postresql.Driver");
            conn = DriverManager.getConnection(url, user, password);
          //System.out.println("Connected to the PostgreSQL server successfully."); 
        } catch (Exception e) {
             e.getMessage();
         }

        return conn;
    }

     public void insertIntoTable(String naam) {
        try {
            conn = this.connect();
            Statement st;
            st = conn.createStatement();
            ResultSet rs = st.executeQuery("INSERT INTO eigenschappen (naam) 
VALUES (" + naam + ")");
            while (rs.next()) {
                System.out.println(rs.getString(1));
            }
        } catch (SQLException e) {
             e.getMessage();
         }
    }
}

The Textfield in Main Class(JavaFx)

Main Class

    TextField contactNaamField = new TextField();
    Button opslaan = new Button("Opslaan");
    Database db = new Database();

     public static void main(String[] args) {
        launch(args);

    }

    public void start(Stage primaryStage) throws Exception {

        opslaan.setOnMouseClicked(e -> {
            String naam = contactNaamField.getText();
             db.insertIntoTable(naam);
        });
    }
}

0 个答案:

没有答案