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:
- Load the database driver (for example, for MySQL:
com.mysql.cj.jdbc.Driver). - Create a connection using
DriverManager.getConnection(url, user, password). - Use the
Connectionobject to create aStatementorPreparedStatementand execute SQL queries. - Process the results via
ResultSet. - 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.