Junior — Middle
How is interaction with a relational database carried out when developing in Java?
sobes.tech AI
Answer from AI
Interaction with a relational database during Java development is usually done using JDBC (Java Database Connectivity) or ORM frameworks such as Hibernate or JPA.
Main steps when using JDBC:
- Loading the database driver.
- Establishing a connection to the database via
DriverManager.getConnection(). - Creating and executing SQL queries using
StatementorPreparedStatement. - Processing results through
ResultSet. - Closing resources.
Example of a simple query using JDBC:
import java.sql.*;
public class DbExample {
public static void main(String[] args) throws SQLException {
String url = "jdbc:mysql://localhost:3306/mydb";
String user = "root";
String password = "password";
Connection conn = DriverManager.getConnection(url, user, password);
String query = "SELECT id, name FROM users";
try (Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query)) {
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
System.out.println(id + ": " + name);
}
}
conn.close();
}
}
Using ORM allows working with Java objects instead of directly with SQL, which simplifies development and code maintenance.