When working with JDBC and ResultSet in Java, handling null values is a common scenario. The ResultSet provides various methods to retrieve data from a database, but it's important to check for null values to avoid potential NullPointerExceptions. Here's how to handle null values properly:
When you retrieve a value from a ResultSet, you can check if it was null in the database by using the wasNull() method of ResultSet. This method returns true if the last column read had a value of SQL NULL.
Consider a table with a nullable column age:
ResultSet rs = statement.executeQuery("SELECT name, age FROM users"); while (rs.next()) { String name = rs.getString("name"); int age = rs.getInt("age"); // getInt returns 0 if the value is SQL NULL if (rs.wasNull()) { // Handle NULL age System.out.println(name + " has an unknown age."); } else { // Handle non-NULL age System.out.println(name + " is " + age + " years old."); } } In this example, getInt on a null value returns 0, which is the default for primitive int. After calling getInt, wasNull() is used to check if the actual value was null.
If the column type maps to an object, you can directly check the retrieved value against null.
ResultSet rs = statement.executeQuery("SELECT name, email FROM users"); while (rs.next()) { String name = rs.getString("name"); String email = rs.getString("email"); // getString returns null if the value is SQL NULL if (email == null) { // Handle NULL email System.out.println(name + " has no email registered."); } else { // Handle non-NULL email System.out.println(name + "'s email is " + email); } } ResultSet getter method for the data type you are working with (like getString for VARCHAR, getInt for INTEGER, etc.).null values in your result set, be prepared to handle them in your application logic.int, double, boolean, etc.) cannot be null in Java. Their respective ResultSet getter methods return a default value if the SQL value is null (like 0 for int, false for boolean). Always check with wasNull() after retrieving a primitive value to accurately determine if it was null in the database.String, Integer, Double, Boolean, etc.), the ResultSet getter methods return null if the SQL value is null. In these cases, you can directly check the retrieved object against null.android-calendar dask ngb-datepicker dplyr keyerror ruby-on-rails-5 resnet azure-storage python-venv qunit