import [Link].
Connection;
import [Link];
import [Link];
import [Link];
import [Link];
// 1. Load MySQL JDBC Driver (optional in newer versions)
// 2. Establish connection
// 3. Create SQL query using PreparedStatement
// 4. Execute query
// 5. Iterate Reseultset
// 6. Close resources
public class DatabaseExample {
public static void main(String[] args) {
// Database credentials
String jdbcURL = "jdbc:mysql://localhost:3306/testdb";
String username = "root";
String password = "password";
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
// 1. Load MySQL JDBC Driver (optional in newer versions)
[Link]("[Link]");
// 2. Establish connection
Connection conn = [Link](jdbcURL, username,
password);
[Link]("Connected to database!");
// 3. Create SQL query using PreparedStatement
String sql = "SELECT id, name, email FROM users WHERE id = ?";
PreparedStatement stmt = [Link](sql);
[Link](1, 1); // Set parameter
// 4. Execute query
rs = [Link]();
// 5. Process result
while ([Link]()) {
int id = [Link]("id");
String name = [Link]("name");
String email = [Link]("email");
[Link](id + " | " + name + " | " + email);
}
} catch (SQLException e) {
[Link]();
} catch (ClassNotFoundException e) {
[Link]();
} finally {
// 6. Close resources
try {
if (rs != null) [Link]();
if (stmt != null) [Link]();
if (conn != null) [Link]();
} catch (SQLException e) {
[Link]();
}
}
}
}