To interact with a database from Java, you can use the Java Database Connectivity (JDBC) API. JDBC provides a set of Java classes and interfaces that allow you to connect to a database, send queries and update statements, and retrieve and process the results.
Here is an example of how to use JDBC to connect to a MySQL database and execute a simple SELECT query:
// Load the JDBC driver Class.forName("com.mysql.jdbc.Driver"); // Connect to the database Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/database", "user", "password"); // Create a statement Statement stmt = conn.createStatement(); // Execute the query ResultSet rs = stmt.executeQuery("SELECT * FROM table"); // Process the results while (rs.next()) { int id = rs.getInt("id"); String name = rs.getString("name"); System.out.println("ID: " + id + ", Name: " + name); } // Close the connection conn.close();
This example loads the MySQL JDBC driver, establishes a connection to the database, creates a statement, executes a SELECT query, and processes the results. It then closes the connection.
For more information on using JDBC to interact with databases in Java, you can refer to the JDBC documentation or other online resources. You may also want to consider using an object-relational mapping (ORM) tool such as Hibernate, which can simplify the process of interacting with a database from Java.