Concept Explanation
Connecting to a database in Java is like making a Phone Call.
- The Dial (Connection): You need the phone number (URL), username, and password to establish a line.
- The Message (Statement): You tell the database what you want (e.g., "Give me all the users!").
- The Answer (ResultSet): The database talks back, and you listen to its answers.
Syntax or Core Structure
String url = "jdbc:mysql://localhost:3306/mydb";
try (Connection conn = DriverManager.getConnection(url, "user", "pass")) {
String sql = "SELECT name FROM users WHERE id = ?";
// PreparedStatements are safer (The "Secure Line")
try (PreparedStatement pst = conn.prepareStatement(sql)) {
pst.setInt(1, 101);
ResultSet rs = pst.executeQuery();
while (rs.next()) {
System.out.println("Name: " + rs.getString("name"));
}
}
} catch (SQLException e) {
e.printStackTrace();
}
Best Practices
- Use try-with-resources: Connections are expensive and rare. Always hang up the phone (close them) when you're done!
- NEVER use Statement for variables: Always use
PreparedStatement. Using normalStatementwith user input leads to SQL Injection, where a hacker can delete your whole database.
Practice Exercises
- The Secure Search: Write a program that takes a
userIdfrom the console and uses aPreparedStatementto fetch that user's email from a database. - The Insert: Research the difference between
executeQuery()andexecuteUpdate(). Which one would you use to add a new user? - Transaction: Research
conn.setAutoCommit(false). How does this allow you to do "All or Nothing" operations?