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


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://java-util.k43.ch/examples/jdbc-database.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
