import java.sql.*; public class Demo { public static void main(String[] args) throws SQLException { // Connect to the database Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "root", "password"); // Create a statement Statement stmt = con.createStatement(); // Execute the query ResultSet rs = stmt.executeQuery("SELECT name FROM persons WHERE id = 1"); // Get the name from the result set if (rs.next()) { String name = rs.getString("name"); System.out.println("Name: " + name); } // Close the resources rs.close(); stmt.close(); con.close(); } }
import java.sql.*; public class Demo { public static void main(String[] args) throws SQLException { // Connect to the database Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "root", "password"); // Create a statement Statement stmt = con.createStatement(); // Execute the query ResultSet rs = stmt.executeQuery("SELECT phone FROM customers WHERE id = 1"); // Get the phone number from the result set if (rs.next()) { String phone = rs.getString(1); System.out.println("Phone: " + phone); } // Close the resources rs.close(); stmt.close(); con.close(); } }These examples use the java.sql package library.