DB Connection from Java code

Connecting ChistaDATA database from Java code

To connect to ClickHouse via Java, you can use the official ClickHouse JDBC driver. Here are the steps to connect to ClickHouse via Java:

  1. Download the ClickHouse JDBC driver from the official website: https://clickhouse.tech/docs/en/getting_started/connect/

  2. Add the ClickHouse JDBC driver JAR file to your project’s classpath.

  3. In your Java code, import the necessary classes:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
  1. In your code, create a connection to ClickHouse using the following code:
// Replace the placeholders with your ClickHouse server information
String url = "jdbc:clickhouse://<host>:<port>/<database>";
String username = "<username>";
String password = "<password>";

// Create the connection
Connection connection = DriverManager.getConnection(url, username, password);
  1. You can now use the Connection object to execute queries against the ClickHouse database. For example:
// Execute a simple query
String query = "SELECT * FROM mytable";
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(query);

// Process the results
while (resultSet.next()) {
    // Do something with the result
}

// Close the resources
resultSet.close();
statement.close();
connection.close();

Note that you should always close the resources (result set, statement, and connection) after using them to free up system resources.