Junior — Middle
What methods do you use to manage database interactions in your projects?
sobes.tech AI
Answer from AI
To manage database interactions in Java projects, the following methods are commonly used:
- JDBC — a basic API for connecting and executing SQL queries.
- ORM frameworks, such as Hibernate or JPA, which simplify working with the database by allowing you to work with objects instead of SQL.
- Using Spring Data, which provides convenient repositories for data access.
Example of using JDBC:
String url = "jdbc:mysql://localhost:3306/mydb";
String user = "root";
String password = "password";
try (Connection conn = DriverManager.getConnection(url, user, password);
Statement stmt = conn.createStatement()) {
ResultSet rs = stmt.executeQuery("SELECT * FROM users");
while (rs.next()) {
System.out.println(rs.getString("username"));
}
} catch (SQLException e) {
e.printStackTrace();
}