Sobes.tech
Junior — Middle

How can a database be accessed to execute a query?

sobes.tech AI

Answer from AI

To access a database in Java, JDBC (Java Database Connectivity) or ORM frameworks like Hibernate or JPA are usually used.

Example using JDBC:

import java.sql.*;

public class DatabaseExample {
    public static void main(String[] args) {
        String url = "jdbc:mysql://localhost:3306/mydb";
        String user = "root";
        String password = "password";

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

This approach allows establishing a connection, preparing a query, executing it, and processing the results.

How can a database be accessed to execute a query… - sobes.tech