Use PostgreSQL JDBC4 driver to connect the database

Connecting the database is an indispensable task in developing applications.In Java, we can use the PostgreSQL JDBC4 driver to implement the connection with the PostgreSQL database.This article will introduce how to connect the database with the PostgreSQL JDBC4 driver and provide the corresponding Java code example. First, we need to download and install the Postgresql JDBC4 driver.You can obtain the latest version of the driver by visiting the official website of PostgreSQL or MAVEN central memory.Add the jar file of the driver to the class path of the Java project. The following is a simple Java code example, which shows how to use the PostgreSQL JDBC4 driver to connect the database, execute the query and output results: import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class PostgreSQLExample { public static void main(String[] args) { // Define the database connection URL, user name and password String url = "jdbc:postgresql://localhost:5432/mydatabase"; String user = "myusername"; String password = "mypassword"; // Define query sentences String query = "SELECT * FROM mytable"; try { // Connect to the database Connection connection = DriverManager.getConnection(url, user, password); // Create a statement object Statement statement = connection.createStatement(); // Execute the query sentence ResultSet resultSet = statement.executeQuery(query); // Process query results while (resultSet.next()) { // Get the data of each line and output int id = resultSet.getInt("id"); String name = resultSet.getString("name"); System.out.println("ID: " + id + ", Name: " + name); } // Close the database connection resultSet.close(); statement.close(); connection.close(); } catch (SQLException e) { e.printStackTrace(); } } } In the above code example, we first define the database connection URL, username and password.Then, we use the `DriverManager.GetConnection () method to create a` Connection "object to build a connection with the database.Next, we create an object of the `Statement` to execute the query statement and use the method of` ExecuteQuery () `to perform the query.Finally, we obtain the query results through the `ResultSet` object and output the data of each line.After completing the database operation, remember to close the database connection to release resources. Summary: This article introduces how to connect the database using the Postgresql JDBC4 driver and provide a simple Java code example.Through these code examples, developers can easily interact with the Postgresql database, perform query operations, and process query results.