Connecting Java to a database — drivers, statements, transactions, batching, and connection pooling.
Question 1: What is JDBC, and why is it needed?
Ans
JDBC, Java Database Connectivity, is the standard Java API that lets a Java application connect to a relational database, send SQL statements, and process the results, without needing to know the low-level details of how each specific database communicates over the network.
JDBC defines the API; each database vendor supplies its own JDBC driver that implements that API for their specific database.
Question 2: What is the difference between Statement, PreparedStatement, and CallableStatement?
Ans
Statement executes plain SQL strings directly, re-parsed by the database every time. PreparedStatement uses parameter placeholders (?) that are compiled once and filled in safely on each execution, which is both faster for repeated use and safe against SQL injection. CallableStatement extends PreparedStatement specifically to call stored procedures in the database.
Example
java
PreparedStatement ps = con.prepareStatement("select * from users where email = ?");
ps.setString(1, email);
CallableStatement cs = con.prepareCall("{call getUserById(?)}");
Important Point
Never build SQL by concatenating untrusted input into a Statement — that's the classic SQL injection vulnerability that PreparedStatement exists to prevent.