Question

I want to search for the id of a movie in a table of the database. I'm new to database connection and new to java as well. This code doesn't have error in my form but I created a record of id '1' and always gives me this error "Java.lang.NullPointerExepton".

I have the record with that id but always have that error. Any help will be appreciated

Connection conn = null;
    ResultSet rs = null;
    PreparedStatement pst = null;

        private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
            // TODO add your handling code here:

    String url = "jdbc:mysql://localhost:3306/project";
            String userid = "root";
            String password = "";

    try{
                String sql="SELECT Movie_idMovie FROM rental_movie"
                        + "WHERE Movie_idMovie =?";
                pst=conn.prepareStatement(sql);
                pst.setString(1, jTextField1.getText());
                rs=pst.executeQuery();
                if(rs.next()){
                    String add1=rs.getString("Movie_idMovie");
                    jTextField2.setText(add1);
                }
            }
            catch(Exception e){
                JOptionPane.showMessageDialog(null,e);
            }
        } 
Was it helpful?

Solution

The problem here is this:

Connection conn = null;

String url = "jdbc:mysql://localhost:3306/project";
String userid = "root";
String password = "";

pst=conn.prepareStatement(sql);

You missed the important step of actually opening the connection, leaving conn null when you try and use it. Try adding the following, before you call conn.prepare...

conn = DriverManager.getConnection(url, userid, password);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top