Sobes.tech
Junior — Middle

How does connecting to a database work in your application?

sobes.tech AI

Answer from AI

In Java, connecting to a database is usually done through JDBC (Java Database Connectivity). The main steps:

  1. Load the database driver (for example, for MySQL: com.mysql.cj.jdbc.Driver).
  2. Create a connection using DriverManager.getConnection(url, user, password).
  3. Use the Connection object to create a Statement or PreparedStatement and execute SQL queries.
  4. Process the results via ResultSet.
  5. Close resources (ResultSet, Statement, Connection) to free resources.

Example of connecting to MySQL:

String url = "jdbc:mysql://localhost:3306/mydb";
String user = "root";
String password = "password";

try (Connection conn = DriverManager.getConnection(url, user, password)) {
    PreparedStatement stmt = conn.prepareStatement("SELECT * FROM users WHERE id = ?");
    stmt.setInt(1, 1);
    ResultSet rs = stmt.executeQuery();
    while (rs.next()) {
        System.out.println(rs.getString("username"));
    }
} catch (SQLException e) {
    e.printStackTrace();
}

Modern applications often use connection pools (e.g., HikariCP) to improve performance and resource management.