Page cover image

🗃️JDBC Database

Simple SQL CRUD operations for any database.

KDB Class Overview

  • Dynamic and Precompiled SQL Support Offers flexibility to execute both dynamic and precompiled SQL statements, catering to a wide range of database interaction needs.

  • Versatile Data Retrieval Retrieve query results in multiple formats: - Java Format: Rows as ArrayList and columns as Java objects. - Serialized Formats: JSON, YAML, XML, CSV, or as a tabular string for enhanced compatibility and readability.

Prerequisites

The KDB database class works with any compliant JDBC drivers. Some popular download sources are listed here. Just place the JAR file in a directory pointed to by the classpath and specify the JDBC class name in the KDB constructor.

Example H2 Database

import ch.k43.util.KDB;
import ch.k43.util.KLog;

public class Database {
	
   public static void main(String[] args) {

      try (KDB db = new KDB(KDB.JDBC_H2, "jdbc:h2:mem:mydb", "", "")) {

         KLog.abort(!db.isConnected(), "Error: {}", db.getErrorMessage());
	
         db.exec("CREATE TABLE addresses (sequence INT AUTO_INCREMENT, lastname VARCHAR(20), firstname VARCHAR(20))");
		   
         db.prepare("INSERT INTO addresses (lastname, firstname) VALUES (?, ?)");
         db.execPrepare("Smith", "Joe");
         db.execPrepare("Miller", "Bob");
         db.execPrepare("Johnson", "Evelyn");
         db.exec("SELECT * FROM addresses");

         System.out.println(db.getDataAsJSON());
      }
   }
}
Output
{
  "ADDRESSES": [
    {
      "SEQUENCE": 1,
      "LASTNAME": "Smith",
      "FIRSTNAME": "Joe"
    },
    {
      "SEQUENCE": 2,
      "LASTNAME": "Miller",
      "FIRSTNAME": "Bob"
    },
    {
      "SEQUENCE": 3,
      "LASTNAME": "Johnson",
      "FIRSTNAME": "Evelyn"
    }
  ]
}

Last updated