{"id":37,"date":"2010-12-05T22:48:23","date_gmt":"2010-12-05T14:48:23","guid":{"rendered":"https:\/\/www.techcoil.com\/blog\/?p=37"},"modified":"2018-09-02T11:30:32","modified_gmt":"2018-09-02T03:30:32","slug":"how-to-handle-null-database-fields-with-java","status":"publish","type":"post","link":"https:\/\/www.techcoil.com\/blog\/how-to-handle-null-database-fields-with-java\/","title":{"rendered":"How to handle null database fields with Java"},"content":{"rendered":"<p>Content is king and large software cannot get away from serving content. In this post, I shall document how to use Java to access relational databases, with the MySQL database as an example. Suppose we have created a database instance with two tables with the following SQL commands:<\/p>\n<pre class=\"brush: sql; title: ; notranslate\" title=\"\">\r\nCREATE DATABASE `db-instance`;\r\nUSE `db-instance`;\r\n\r\nCREATE TABLE Job (\r\n        `id` INT NOT NULL AUTO_INCREMENT,\r\n        `name` VARCHAR(255),\r\n        `description` TEXT,\r\n        PRIMARY KEY(id)\r\n) ENGINE=INNODB;\r\n\r\nCREATE TABLE Person (\r\n\t`id` INT NOT NULL AUTO_INCREMENT,\r\n\t`name` VARCHAR(255),\r\n\t`address` VARCHAR(255),\r\n\t`job-id` INT,\r\n\tPRIMARY KEY (ID),\r\n        FOREIGN KEY (`job-id`) REFERENCES Job(`id`)\r\n) ENGINE=INNODB;\r\n<\/pre>\n<p>\nThe above SQL commands will create a Job table and a Person table in the db-instance database.\n<\/p>\n<h3>Steps to interact with the database through JDBC<\/h3>\n<ul>\n<li>Load the database driver.<\/li>\n<li>Provide a username and password pair and name of database instance to get a Connection object.<\/li>\n<li>Create a Statement object from the Connection object.<\/li>\n<li>Use the Statement object to execute SQL commands to interact with the database.<\/li>\n<\/ul>\n<h3>Sample code to interact with the database through the JDBC api.<\/h3>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\nConnection dbConnection = null;\r\ntry {\r\n     \/\/ Load the MySQL driver\r\n     Class.forName(&quot;com.mysql.jdbc.Driver&quot;);\r\n     \/\/ Connect to the database instance (db-instance)\r\n     \/\/ @ localhost with a user account (identified by user and password).\r\n     dbConnection = DriverManager.getConnection(&quot;jdbc:mysql:\/\/localhost\/&quot;\r\n             + &quot;db-instance&quot;, &quot;user&quot;, &quot;password&quot;);\r\n     \/\/ Execute a SQL select statement on the database.\r\n     Statement sqlStat = dbConnection.createStatement();\r\n     ResultSet sqlResult = sqlStat.executeQuery(&quot;SELECT * FROM Person&quot;);\r\n     \/\/ Traverse sqlResult\r\n     while(sqlResult .next()) {\r\n         \/\/ Get the value of job-id\r\n         int jobId = sqlResult.getInt(&quot;job-id&quot;);\r\n         System.out.println(&quot;Job ID: &quot; + jobId);\r\n     } \/\/ end while\r\n\r\n} catch (ClassNotFoundException cnfe) {\r\n     System.out.println(cnfe.getMessage());\r\n} catch (SQLException sqle) {\r\n     System.out.println(sqle);\r\n} finally {\r\n     \/\/ Free up resources used\r\n     if (dbConnection != null) {\r\n         try {\r\n             dbConnection.close();\r\n         } catch (SQLException sqle) {\r\n             \/\/ Swallow any exceptions when closing the connection.\r\n         } \/\/ end try-catch block\r\n     } \/\/ end if\r\n} \/\/ end try-catch block\r\n<\/pre>\n<h3>What is wrong with the above code?<\/h3>\n<p>\nBased on the database schema shown earlier, we can see that the job-id column of the Person table can contain null values. However, in the above coding, we are using the <code>getInt()<\/code> method of the <code>ResultSet<\/code> class to retrieve a the job-id value. The int data type being one of Java's primitive types is not able to store the null. On my machine, the <code>getInt()<\/code> method returns 0 when it hits a null on the job-id.\n<\/p>\n<h3>How to solve the problem?<\/h3>\n<p>\nThere are two ways to detect whether a null value is read.\n<\/p>\n<p>\n1) Use the <code>wasNull()<\/code> method provided by the ResultSet class.\n<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\n\/\/ Traverse sqlResult\r\nwhile(sqlResult.next()) {\r\n    \/\/ Get the value of job-id\r\n    int jobId = sqlResult.getInt(&quot;job-id&quot;);\r\n    \/\/ if jobId is supposed to be null\r\n    if (sqlResult.wasNull()) {\r\n            System.out.println(&quot;Job ID: null&quot;);\r\n    } else {\r\n            System.out.println(&quot;Job ID: &quot; + jobId);\r\n    }\r\n} \/\/ end while\r\n<\/pre>\n<p>\n2) Use the <code>getObject()<\/code> method instead of the <code>getInt()<\/code> method to retrieve the value of the job-id column. By using the <code>getObject()<\/code> method, we are able to get null values if there any appears.\n<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\n\/\/ Traverse sqlResult\r\nwhile(sqlResult.next()) {\r\n    Object jobId = sqlResult.getObject(&quot;job-id&quot;);\r\n    if (jobId == null) {\r\n        System.out.println(&quot;Job ID: null&quot;);\r\n    } else {\r\n        System.out.println(&quot;Job ID: &quot; + jobId);\r\n    } \/\/ end if (jobId == null)\r\n} \/\/ end while\r\n<\/pre>\n\n      <ul id=\"social-sharing-buttons-list\">\n        <li class=\"facebook\">\n          <a href=\"https:\/\/www.facebook.com\/sharer\/sharer.php?u=https%3A%2F%2Fwp.me%2Fp245TQ-B\" target=\"_blank\" role=\"button\" rel=\"nofollow\">\n            <img decoding=\"async\" src=\"\/ph\/img\/3rd-party\/social-icons\/Facebook.png\" alt=\"Facebook icon\"> Share\n          <\/a>\n        <\/li>\n        <li class=\"twitter\">\n          <a href=\"https:\/\/twitter.com\/intent\/tweet?text=&url=https%3A%2F%2Fwp.me%2Fp245TQ-B&via=Techcoil_com\" target=\"_blank\" role=\"button\" rel=\"nofollow\">\n          <img decoding=\"async\" src=\"\/ph\/img\/3rd-party\/social-icons\/Twitter.png\" alt=\"Twitter icon\"> Tweet\n          <\/a>\n        <\/li>\n        <li class=\"linkedin\">\n          <a href=\"https:\/\/www.linkedin.com\/shareArticle?mini=1&title=&url=https%3A%2F%2Fwp.me%2Fp245TQ-B&source=https:\/\/www.techcoil.com\" target=\"_blank\" role=\"button\" rel=\"nofollow\">\n          <img decoding=\"async\" src=\"\/ph\/img\/3rd-party\/social-icons\/linkedin.png\" alt=\"Linkedin icon\"> Share\n          <\/a>\n        <\/li>\n        <li class=\"pinterest\">\n          <a href=\"https:\/\/pinterest.com\/pin\/create\/button\/?url=https%3A%2F%2Fwww.techcoil.com%2Fblog%2Fwp-json%2Fwp%2Fv2%2Fposts%2F37&description=\" class=\"pin-it-button\" target=\"_blank\" role=\"button\" rel=\"nofollow\" count-layout=\"horizontal\">\n          <img decoding=\"async\" src=\"\/ph\/img\/3rd-party\/social-icons\/Pinterest.png\" alt=\"Pinterest icon\"> Save\n          <\/a>\n        <\/li>\n      <\/ul>\n    ","protected":false},"excerpt":{"rendered":"<p>Content is king and large software cannot get away from serving content. In this post, I shall document how to use Java to access relational databases, with the MySQL database as an example. <\/p>\n","protected":false},"author":1,"featured_media":1045,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"advanced_seo_description":"","jetpack_seo_html_title":"","jetpack_seo_noindex":false,"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":true,"_jetpack_newsletter_tier_id":0,"footnotes":""},"categories":[375],"tags":[6,10,9],"jetpack_featured_media_url":"https:\/\/www.techcoil.com\/blog\/wp-content\/uploads\/java-logo.jpg","jetpack_shortlink":"https:\/\/wp.me\/p245TQ-B","jetpack-related-posts":[],"jetpack_likes_enabled":true,"jetpack_sharing_enabled":true,"_links":{"self":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/posts\/37"}],"collection":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/comments?post=37"}],"version-history":[{"count":0,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/posts\/37\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/media\/1045"}],"wp:attachment":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/media?parent=37"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/categories?post=37"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/tags?post=37"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}