0

I have connected my DB with eclipse and i want to give the administrator the permission to delete a member putting the members id from Scanner from a table that I have created

public void processDelete() {
          try {
                String url = "jdbc:mysql://localhost:3306/labdb";
                String user = "****";
                String password = "***";
                
                Connection myConn = null;
                myStmt = null;
                ResultSet myRs = null;
                Scanner keyboard=new Scanner(System.in);
                
                System.out.println("Enter the id you want to delete");
                int id=keyboard.nextInt();
                
                 int rowsAffect=myStmt.executeUpdate(
                            "delete from members " +
                            "where member_id='"+id+"' ");
            } catch (Exception exc) {
                exc.printStackTrace();
            }

and i get this error

java.lang.NullPointerException
    at DeleteMembers.processDelete(DeleteMembers.java:24)
    at main.main(main.java:67)
Bill Zois
  • 1
  • 1

1 Answers1

0

You get the java.lang.NullPointerException because both your Connection and Statement are null.

You first need to initialize Connection by connectiong with your database.

Use :

Class.forName("YourDriver").newInstance();

to register your databese driver,

myConn = DriverManager.getConnection(dbURL);

To inisialize your Connection

Then you should do :

myStmt = myConn.createStatement()

To inisialize Statement

And after all that you can use your statement to exequte a query in the database

AirlineDog
  • 520
  • 8
  • 21
  • The `.newInstance()` in `Class.forName("YourDriver").newInstance();` has never been necessary (except with certain very old and very buggy version of MySQL Connector/J), and `Class.forName("YourDriver")` hasn't been necessary in simple Java applications since Java 6 (with a JDBC 4 driver), and is only necessary when the driver isn't on the initial classpath (eg in web applications with the driver in WEB-INF/lib). – Mark Rotteveel Dec 25 '20 at 14:30