How does Java interact with databases

Java interacts with databases primarily through the Java Database Connectivity (JDBC) API. JDBC is a standard API that allows Java applications to connect to multiple types of databases, execute SQL queries, and manage the results. By using JDBC, developers can establish a connection to a database, execute SQL commands, and retrieve data in a Java-friendly way.

Example of Java Database Interaction

import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; public class DatabaseExample { public static void main(String[] args) { Connection connection = null; Statement statement = null; ResultSet resultSet = null; try { // Load database driver Class.forName("com.mysql.cj.jdbc.Driver"); // Establish connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "username", "password"); // Create a statement statement = connection.createStatement(); // Execute a query resultSet = statement.executeQuery("SELECT * FROM users"); // Process the results while (resultSet.next()) { System.out.println("User ID: " + resultSet.getInt("id")); System.out.println("Username: " + resultSet.getString("username")); } } catch (Exception e) { e.printStackTrace(); } finally { // Clean up try { if (resultSet != null) resultSet.close(); if (statement != null) statement.close(); if (connection != null) connection.close(); } catch (Exception e) { e.printStackTrace(); } } } }

Java JDBC Database Connectivity SQL Java Database Interaction