Here’s a sample code snippet that demonstrates how to read data from a MySQL database using Java and JDBC (Java Database Connectivity:
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class MySQLDataReader { public static void main(String[] args) { // Database credentials String url = "jdbc:mysql://localhost:3306/mydatabase"; String username = "root"; String password = "password"; // SQL query String query = "SELECT * FROM customers"; try { // Register JDBC driver Class.forName("com.mysql.cj.jdbc.Driver"); // Open a connection Connection conn = DriverManager.getConnection(url, username, password); // Create a statement Statement stmt = conn.createStatement(); // Execute the query ResultSet rs = stmt.executeQuery(query); // Process the result set while (rs.next()) { int id = rs.getInt("id"); String name = rs.getString("name"); String email = rs.getString("email"); System.out.println("ID: " + id); System.out.println("Name: " + name); System.out.println("Email: " + email); System.out.println("--------------------------"); } // Close the resources rs.close(); stmt.close(); conn.close(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } } }
Make sure to replace the url
, username
, and password
variables with your actual MySQL database connection details. Additionally, modify the query
variable to match your desired SQL query.
This code snippet assumes you have the MySQL JDBC driver (e.g., mysql-connector-java.jar
) included in your classpath. If not, you can download it from the official MySQL website or include it as a Maven/Gradle dependency.
The code connects to the MySQL database, executes the SQL query, and iterates over the result set to retrieve the data. In this example, it assumes a table named “customers” with columns “id,” “name,” and “email.” Adjust the column names as per your table schema.