I want to insert values to my database table made in ms access. This code works before and I can’t understand why it gets some error now.
Exception in thread "main" java.lang.NullPointerException
at storeapp.Trylog.<init>(Trylog.java:28)
at storeapp.Trylog.main(Trylog.java:45)
I believe I configured the driver correctly.
I have a table name ACCOUNT with columns Username and Password..
And here is the code…..
public class Trylog extends JFrame{
Connection con;
Statement st;
ResultSet rs;
public Trylog(){
connect();
String u = "Katherine";
String p = "kat";
String sql = "Insert into ACCOUNT(Username, Password) Values ('"+u+"' , '"+p+"' ) ";
try {
rs = st.executeQuery(sql);
} catch (SQLException ex) {
}
}
public void connect(){
try {
String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
Class.forName(driver);
String db = "jdbc:odbc:access";
con = DriverManager.getConnection(db);
st = con.createStatement();
}
catch (Exception ex){}
}
public static void main(String[] args) {
Trylog r = new Trylog();
r.setVisible(true);
r.setSize(600, 800);
r.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Do anyone know why I get such error?
This is the line that cause the exception base from line 28 and 46
rs = st.executeQuery(sql);
and
Trylog r = new Trylog();
It prints
Exception in thread "main" java.lang.RuntimeException: java.sql.SQLException: No ResultSet was produced
Caused by: java.sql.SQLException: No ResultSet was produced
Your concrete problem is caused by bad exception handling (even more, there’s no exception handling at all). You’ve there catch blocks which completely swallows the exception, such as here:
This way the code continues to run in case of an exception, possibly leaving the variables in the
tryblock such asstuninitialized. After that, those uninitialized (i.e. they are stillnull) variables are been accessed which in turn causes theNullPointerException.This shouldn’t happen. When an exception is caught, the code should properly deal with it. In this case, it should stop immediately and show the error detail in some way. At this moment, easiest is to rethrow it as a runtime exception so that you will at least get all the necessary information about the problem:
(you can always improve this by logging the stacktrace and showing some user friendly message dialog and then exiting the program, for example)
The thrown exception is basically the whole answer to the root cause of your problem. The art is to be able to interpret and understand the stacktrace.
Update as per your update, you got
See, there’s your answer! There’s no
ResultSetbeen produced at all for the given query, while you expected it to be produced. And indeed, anINSERTquery won’t return a result set. It will at highest return the amount of affected rows.You need to replace
by
See also the
executeQuery()javadoc and theexecuteUpdate()javadoc. They precisely tell for which SQL statements the method should be used.