import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class ConnectionExample { public static void main(String[] args) { Connection connection = null; try { Class.forName("org.postgresql.Driver"); String url = "jdbc:postgresql://localhost:5432/mydatabase"; String username = "myusername"; String password = "mypassword"; connection = DriverManager.getConnection(url, username, password); System.out.println("Connection successful!"); } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); } finally { try { if (connection != null) { connection.close(); } } catch (SQLException e) { e.printStackTrace(); } } } }
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class StatementExample { public static void main(String[] args) { Connection connection = null; Statement statement = null; ResultSet resultSet = null; try { Class.forName("org.postgresql.Driver"); String url = "jdbc:postgresql://localhost:5432/mydatabase"; String username = "myusername"; String password = "mypassword"; connection = DriverManager.getConnection(url, username, password); statement = connection.createStatement(); resultSet = statement.executeQuery("SELECT * FROM mytable"); while (resultSet.next()) { System.out.println(resultSet.getString("column1")); } } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); } finally { try { if (resultSet != null) { resultSet.close(); } if (statement != null) { statement.close(); } if (connection != null) { connection.close(); } } catch (SQLException e) { e.printStackTrace(); } } } }In this example, we use the `Connection.createStatement` method to create a `Statement` object, and then we use the `Statement.executeQuery` method to execute a SQL `SELECT` statement. We then iterate over the `ResultSet` object returned by `executeQuery` using the `ResultSet.next` method, and print the value of the `column1` field for each record. Finally, we close the `ResultSet`, `Statement`, and `Connection` objects in a `finally` block to ensure that they are properly cleaned up. This example also uses the `java.sql` package, which is part of the JDBC API.