java - get Nullpointerexception while insert records -
this question has answer here:
- what nullpointerexception, , how fix it? 12 answers
i trying insert data database using prepare statements 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 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 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 wrong in code ?
conn
null in savebuttonactionperformed. initialize in item
class:
public class items extends javax.swing.jframe { connection conn = drivermanager.getconnection("jdbc:sqlite:e:\\netbeansprojects\\abdo`s project\\project.sqlite");
you can initialize inside method, sure initialize before use it.