I am getting a java.lang.NullPointerException on calling ResultSet.getDate() in the following code. The entry in the database, however, doesn't seem to be null. The connection seems to be active, since other fields are being fetched.
What am I doing wrong?
try {
... /* Code that creates a connection and initializes statement */
String query = "SELECT * FROM groups WHERE id = 'testGroup1'";
ResultSet rs = statement.executeQuery(query);
if(rs.next()) {
admin = rs.getString("admin_id");
User.process(admin);
java.sql.Date created_on = rs.getDate("created_on");
System.out.println("Created on = " + created_on.toString());
}
}
catch(Exception e) {
System.out.println("Stuck here");
e.printStackTrace();
}
Here's the output and the stack trace:
Admin id = 42 // User.process prints the admin id
Stuck here
java.lang.NullPointerException
at com.mysql.jdbc.ResultSet.findColumn(ResultSet.java:966)
at com.mysql.jdbc.ResultSet.getDate(ResultSet.java:1988)
at com.myapp.server.model.Group.initInfo(Group.java:39)
...
I have the following schema:
+-------------------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------------------+--------------+------+-----+---------+-------+
| id | varchar(50) | NO | PRI | NULL | |
| admin_id | varchar(50) | NO | MUL | NULL | |
| created_on | datetime | NO | | NULL | |
+-------------------+--------------+------+-----+---------+-------+
And the following entry in the database:
+------------+----------+---------------------+
| id | admin_id | created_on |
+------------+----------+---------------------+
| testGroup1 | 42 | 2014-12-15 22:46:31 |
+------------+----------+---------------------+
As mentioned in this question,could you try sthg like that;
I take the code also from the question I mentioned above.
Timestamp timestamp = resultSet.getTimestamp(i);
if (timestamp != null)
date = new java.util.Date(timestamp.getTime()));
The Type of the field created_onin your database is datetime, this is not the same as the Java Date
You'll need to convert it.
If you look at the first answer at this question you'll see how to fix it
I found User.process further queried the database thereby closing the current ResultSet (or so I speculate). The NullPointerException goes away when I do the following:
try {
...
if(rs.next()) {
admin = rs.getString("admin_id");
java.sql.Timestamp created_on = rs.getTimestamp("created_on");
User.process(admin);
}
}
catch(Exception e) {
...
}
Also using getTimestamp() as suggested by other solutions gets me the desired result.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With