0

I trying to insert data to my database using prepare statements but I get Nullpointerexception

My Database connection code

public class DBConnect {
    Connection conn=null;

      public static Connection connecrDb(){
          try{
          Class.forName("org.sqlite.JDBC");
          Connection conn = DriverManager.getConnection("jdbc:sqlite:E:\\NetBeansProjects\\Abdo`s Project\\project.sqlite");
              System.out.println("connection success");
              conn.setAutoCommit(false);
          return conn;
          }
          catch(Exception e){
              JOptionPane.showMessageDialog(null, e);
              return null;
          }
      }

}

and my code in Main Class

public class Items extends javax.swing.JFrame {


    Connection conn =null;
    ResultSet rs = null;
    PreparedStatement pst=null;
    public Items() {
        initComponents();
        DBConnect.connecrDb();
    }

    private void SaveBtnActionPerformed(java.awt.event.ActionEvent evt) {                                        

        try{


           String sql = "INSERT INTO test (name) values(?)";
           pst=conn.prepareStatement(sql);
           pst.setString(1,item_name.getText() );
           pst.executeUpdate(); 
           conn.commit();
        }
        catch(Exception e ){
                      System.out.println(e);
            System.out.println(e.getStackTrace());  
        }


    } 

Output is

java.lang.NullPointerException

[Ljava.lang.StackTraceElement;@7da469fe

what is wrong in my code ?

Buhake Sindi
  • 87,898
  • 29
  • 167
  • 228
  • Please replace `System.out.println(e.getStackTrace());` by `e.printStackTrace(System.out);` and edit the question with the proper stack trace. – Luiggi Mendoza Apr 09 '15 at 20:09
  • 2
    well `conn` is `null` everywhere except in the `connecrDb` method. You need to assign its return value... – Reimeus Apr 09 '15 at 20:10

1 Answers1

0

conn is null in SaveButtonActionPerformed. Initialize it in the Item class:

public class Items extends javax.swing.JFrame {

    Connection conn = DriverManager.getConnection("jdbc:sqlite:E:\\NetBeansProjects\\Abdo`s Project\\project.sqlite");

You can also initialize it inside your method, but just be sure to initialize it before you use it.

mmking
  • 1,564
  • 4
  • 26
  • 36