# JDBC 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.

* [MVN Repository JDBC Drivers](https://mvnrepository.com/open-source/jdbc-drivers)
* [SoapUI JDBC Driver List](https://www.soapui.org/docs/jdbc/reference/jdbc-drivers/)
* [BenchResources.Net JDBC driver](https://www.benchresources.net/jdbc-driver-list-and-url-for-all-databases/)

### Example H2 Database

<pre class="language-java"><code class="lang-java">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());
<strong>      }
</strong>   }
}
</code></pre>

<details>

<summary>Output</summary>

```json
{
  "ADDRESSES": [
    {
      "SEQUENCE": 1,
      "LASTNAME": "Smith",
      "FIRSTNAME": "Joe"
    },
    {
      "SEQUENCE": 2,
      "LASTNAME": "Miller",
      "FIRSTNAME": "Bob"
    },
    {
      "SEQUENCE": 3,
      "LASTNAME": "Johnson",
      "FIRSTNAME": "Evelyn"
    }
  ]
}
```

</details>
