Interview question
What is JDBC and what are the steps to connect Java to a database? JDBC क्या है और Java को database से connect करने के steps क्या हैं?
Answer
JDBC (Java Database Connectivity) is a standard Java API that lets applications interact with relational databases using SQL, regardless of which database vendor is used underneath.
| Step | Action |
|---|---|
| 1 | Load the JDBC driver (auto-loaded via SPI since Java 6+) |
| 2 | Establish a Connection using DriverManager |
| 3 | Create a Statement/PreparedStatement |
| 4 | Execute the SQL query |
| 5 | Process the ResultSet |
| 6 | Close resources (Connection, Statement, ResultSet) |
import java.sql.*;
public class JdbcExample {
public static void main(String[] args) {
String url = 'jdbc:mysql://localhost:3306/mydb';
String user = 'root';
String password = 'password';
try (Connection conn = DriverManager.getConnection(url, user, password);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery('SELECT id, name FROM users')) {
while (rs.next()) {
int id = rs.getInt('id');
String name = rs.getString('name');
System.out.println(id + ': ' + name);
}
} catch (SQLException e) {
System.out.println('Database error: ' + e.getMessage());
}
// try-with-resources closes Connection, Statement, and ResultSet automatically
}
}JDBC (Java Database Connectivity) एक standard Java API है जो applications को SQL इस्तेमाल करके relational databases से interact करने देता है, चाहे कोई भी database vendor हो।
| Step | Action |
|---|---|
| 1 | JDBC driver load करना |
| 2 | DriverManager से Connection बनाना |
| 3 | Statement/PreparedStatement बनाना |
| 4 | SQL query execute करना |
| 5 | ResultSet process करना |
| 6 | Resources close करना |
import java.sql.*;
public class JdbcExample {
public static void main(String[] args) {
String url = 'jdbc:mysql://localhost:3306/mydb';
String user = 'root';
String password = 'password';
try (Connection conn = DriverManager.getConnection(url, user, password);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery('SELECT id, name FROM users')) {
while (rs.next()) {
int id = rs.getInt('id');
String name = rs.getString('name');
System.out.println(id + ': ' + name);
}
} catch (SQLException e) {
System.out.println('Database error: ' + e.getMessage());
}
}
}Was this answer clear?