JDBC in Java — Java Technical Interview Questions & Answers
JDBC in Java
JDBC in Java
- JDBC is Java’s standard way to talk to a database with SQL. Five steps: get a driver for that database brand → open a Connection (URL, user, password) → create Statement or PreparedStatement → execute and read ResultSet row by row → close resources (try-with-resources is best).
- Prefer PreparedStatement. It avoids SQL injection and can reuse plans. Never paste user input into SQL with string concatenation.
- Recite the five steps, then say why PreparedStatement is safer.
- Let's take this on the board with one tiny Main class — no extra files. JDBC in Java — this Main really runs. If MySQL school DB is up, it prints Connected to school DB. If not, catch prints No DB yet + exception class. Steps stay: connect → prepare → execute → read → close. Start from main, go line by line, and stop at each print. That output is the proof for JDBC.
Driver → Connection → Statement
│
▼
ResultSet → closeTechnical Interview Tip: Five steps + why PreparedStatement is safer.
Code Examples for JDBC in Java
Example
import java.sql.DriverManager;
import java.sql.SQLException;
public class Main {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/school";
try {
DriverManager.getConnection(url, "root", "secret");
System.out.println("Connected to school DB");
} catch (SQLException e) {
System.out.println("No DB yet: " + e.getClass().getSimpleName());
}
}
}JDBC in Java — this Main really runs. If MySQL school DB is up, it prints Connected to school DB. If not, catch prints No DB yet + exception class. Steps stay: connect → prepare → execute → read → close.
How to Explain JDBC in Java to an Interviewer
What is JDBC?
Java API to talk to databases with SQL
Name the five steps.
Driver Connection Statement ResultSet Close
Why PreparedStatement?
Safer against SQL injection Can reuse plans