My code is supposed to search a record within the database which contains id typed into IDname JTextField. Suddenly I've got this error:
java.lang.NullPointerException
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
java.lang.NullPointerException
at com.implementer.escuel.Implementing$1.actionPerformed(Implementing.java:55)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
What should I do? String id is defined so why get(id) shows NPE? Are the two errors connected? I also do not quite understand why I've got that ClassNotFoundException also. Here is the code:
JTextField IDname;
JButton submit;
public static Connection getConnection() throws Exception{
try{
String driver = "com.mysql.jdbc.Driver";
String url = "someurl";
String username = "";some name
String password = "some password";
Class.forName(driver);
Connection conn = DriverManager.getConnection(url,username,password);
System.out.println("Connected");
return conn;
} catch(Exception e){System.out.println(e);}
return null;
}
public Implementing() {
IDname = new JTextField("");
submit = new JButton("go");
add(IDname);
add(submit);
submit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(e.getSource() == submit) {
try {
String id = IDname.getText().toString();
getConnection();
////////NEXT LINE IS THE NPE////////
for(String string:get(id)){
System.out.println(string);
}
// get(id);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
});
setLayout(new GridLayout());
}
public ArrayList<String> get(String idname) throws Exception{
try{
Connection con = getConnection();
// You should replace "YourTableName" With table in databace that you work with it
PreparedStatement statement = con.prepareStatement("SELECT * FROM YourTableName WHERE ppname = '" +idname+"'");
//If type of your id in database is Int write this code :
// int id= Integer.parseInt(idName);
//PreparedStatement statement = con.prepareStatement("SELECT * FROM YourTableName WHERE id = " + idName);
ResultSet result = statement.executeQuery();
}