-1

I'm having a NullPointerException error when I run my program, I've read a few things on it and tried to make some changes but still getting the error. here's the code :

public class Farm {
private Connection connect;
private PreparedStatement prep;
public Farm(){
    try {
        Class.forName("oracle.jdbc.OracleDriver");
        DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE", "SHID","pikachu");

    } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

public void AddAnimal(String name, int age, double weight, String specie){

    String sql="INSERT INTO ANIMALFARM VALUES('"+name+"',"+age+", "+weight+",'"+specie+"')";
    try {
        prep= connect.prepareStatement(sql);

        prep.executeUpdate();

    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}}

My main class:

public class Test {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    Farm ferme= new Farm();
    ferme.AddAnimal("Cerbre", 43, 34.00, "dog");
}}

And I'm having this error

Exception in thread "main" java.lang.NullPointerException
at Farm.AddAnimal(Farm.java:31)
at Test.main(Test.java:7)
Shid
  • 1,336
  • 1
  • 15
  • 18

3 Answers3

3

You must link your connect variable to your database

connect = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE", "SHID","pikachu");

if you don't do that connect will be null, so you get a NullPointerException

creekorful
  • 351
  • 4
  • 14
1

Your connect is not initialized to a Connection object. you need to assign it with connection object to fix it

connect =  DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE", "SHID","pikachu");
Sanjeev
  • 9,876
  • 2
  • 22
  • 33
0

by looking at your code,I see that connect is not initialized and this may be the main reason for NPE.

You need to initialize before making any operation on it.

You have declared connect here private Connection connect;; and then you are calling prep= connect.prepareStatement(sql);.

As you know instance variables are by default null and so any operation on null gives nullpointerexception

SpringLearner
  • 13,738
  • 20
  • 78
  • 116