Use DuckDB JDBC driver to connect Java class library: steps and examples
Use DuckDB JDBC driver to connect Java class library: steps and examples
DuckDB is an efficient memory column storage database with built -in analysis function and extensive database support.Through the JDBC driver, you can easily connect and operate the DuckDB database in Java applications.Here are steps and examples of using the DuckDB JDBC driver to connect the Java class library.
Step 1: Download and configure DuckDB JDBC driver
First, download DuckDB JDBC driver from DuckDB's official website (https://duckdb.org/).After downloading, add the jar file of the drive to the class path of the Java project.
Step 2: Import the required class library
In the Java class library, the following class library needs to be introduced to use the DuckDB JDBC driver:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
Step 3: Connect to DuckDB database
Use the following code example to connect to the DuckDB database:
public class DuckDBExample {
public static void main(String[] args) {
// jdbc connection string
String jdbcUrl = "jdbc:duckdb:";
try {
// Load DuckDB driver
Class.forName("org.duckdb.JdbcDriver");
// Connect to DuckDB database
Connection connection = DriverManager.getConnection(jdbcUrl);
// Create a statement object
Statement statement = connection.createStatement();
// Execute the query sentence
ResultSet resultSet = statement.executeQuery("SELECT * FROM my_table");
// Process query results
while (resultSet.next()) {
// Get the value of the column
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
// Output results
System.out.println("ID: " + id + ", Name: " + name);
}
// Turn off the connection
resultSet.close();
statement.close();
connection.close();
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
}
The above code demonstrates the connection to the DuckDB database and executes a simple query statement.Can be modified and expanded according to the actual situation.
It should be noted that if the DuckDB database is running on the remote server, the corresponding host name, port number, user name and password need to be provided to connect.You can use the method to specify these parameters with the method of `DriverManager.getConnection (String URL, String User, String Password).
Summarize:
Through the above steps, you can use the DuckDB JDBC driver to connect the Java class library.A variety of SQL queries and operations can be performed to interact with the DuckDB database.By modifying the example code, you can expand and customize according to your own needs.