Java JDBC परिचय
In this page:
Connection connection = DriverManager.getConnection(url, user, password);
Statement statement = connection.createStatement();
ResultSet result = statement.executeQuery("SELECT * FROM table_name");
JDBC Driver Registration
किसी database से connect होने से पहले, किसी Java application को अपने classpath पर database का JDBC driver चाहिए। Modern JDBC (4.0+) service discovery के ज़रिए driver को अपने आप load करता है, लेकिन पुराने Class.forName() manual-loading pattern को समझना उन legacy configurations को maintain करते समय अब भी मदद करता है जो उस mechanism से पहले की हैं।
उदाहरण: JDBC Driver Registration
public class Main {
public static void main(String[] args) {
try {
Class.forName("org.sqlite.JDBC"); // legacy manual-loading pattern
} catch (ClassNotFoundException e) {
System.out.println("Modern JDBC 4.0+ loads drivers automatically instead");
}
}
}
Login to try C/C++/Java/PHP code in the editor
Creating a Database Connection
एक Connection object database के साथ एक खुले session को represent करता है, और एक पाना आमतौर पर किसी database operation का सबसे महंगा step होता है (network handshake, authentication, session setup)। Tests लिखते समय हम standard interfaces और dynamic proxy handlers का उपयोग करके connection-related operations को साफ़ तरीके से simulate कर सकते हैं, किसी असली database की ज़रूरत से बचते हुए।
उदाहरण: Creating a Database Connection
// Import java.lang.reflect.* so it can be used by its short name
import java.lang.reflect.*;
// Import java.sql.Connection so it can be used by its short name
import java.sql.Connection;
// Define the class Main
public class Main {
// Program entry point: the JVM starts running here
public static void main(String[] args) {
Connection fakeConnection = (Connection) Proxy.newProxyInstance(
Main.class.getClassLoader(),
new Class[]{Connection.class},
(proxy, method, methodArgs) -> {
if (method.getName().equals("isClosed")) return false;
// Send null back to the caller
return null;
}
);
// Print a line to the console
System.out.println("Simulated connection created without a real database");
}
}
Login to try C/C++/Java/PHP code in the editor
Retrieving ResultSet
एक ResultSet object किसी query से return हुए tabular data पर एक cursor को represent करता है। आप हर row के columns निकालने के लिए इसके typed getter methods (getString, getInt, वगैरह) call करते हैं, next() के false return करने तक अगली row पर बढ़ते हुए।
उदाहरण: Retrieving ResultSet
// Import java.lang.reflect.* so it can be used by its short name
import java.lang.reflect.*;
// Import java.sql.ResultSet so it can be used by its short name
import java.sql.ResultSet;
import java.util.*;
// Define the class Main
public class Main {
// Program entry point: the JVM starts running here
public static void main(String[] args) throws Exception {
Iterator<String> rows = List.of("Riya", "Aman").iterator();
ResultSet fakeResultSet = (ResultSet) Proxy.newProxyInstance(
Main.class.getClassLoader(),
new Class[]{ResultSet.class},
(proxy, method, methodArgs) -> switch (method.getName()) {
case "next" -> rows.hasNext();
case "getString" -> rows.next();
default -> null;
}
);
// Repeat while fakeResultSet.next() is true
while (fakeResultSet.next()) {
// Print a line to the console
System.out.println(fakeResultSet.getString("name"));
}
}
}
Login to try C/C++/Java/PHP code in the editor
Executing SQL Statements
JDBC आपको SQL execute करने के दो मुख्य तरीके देता है: basic Statement interface, और PreparedStatement, जो query को पहले से compile करता है और parameters को सुरक्षित रूप से bind करता है। जब भी user input शामिल हो तो PreparedStatement को जोरदार प्राथमिकता दी जाती है, क्योंकि यह SQL structure को data से अलग करता है और SQL injection रोकता है।
उदाहरण: Executing SQL Statements
public class Main {
public static void main(String[] args) {
String userInput = "O'Reilly";
String unsafe = "SELECT * FROM books WHERE author = '" + userInput + "'"; // vulnerable to SQL injection
String safe = "SELECT * FROM books WHERE author = ?"; // PreparedStatement binds userInput separately
System.out.println(unsafe);
System.out.println(safe + " -- bound param: " + userInput);
}
}
Login to try C/C++/Java/PHP code in the editor
Closing JDBC Resources
Connections, statements, और result sets सभी native database resources पकड़े रहते हैं और काम खत्म होने पर इन्हें explicitly close करना चाहिए। Java का try-with-resources syntax इन्हें अपने आप close कर देता है -- operation के बीच में exception फेंके जाने पर भी -- जो समय के साथ चुपचाप खुले connections leak होने से बचने का सबसे आसान तरीका है।
उदाहरण: Closing JDBC Resources
public class Main {
static class FakeResource implements AutoCloseable {
public void close() { System.out.println("Resource closed automatically"); }
}
public static void main(String[] args) {
try (FakeResource conn = new FakeResource(); FakeResource stmt = new FakeResource()) {
System.out.println("Using resources");
} // both closed automatically, even if an exception was thrown
}
}
Login to try C/C++/Java/PHP code in the editor
- पहले
next()call किए बिना किसीResultSetसे पढ़ना, क्योंकि cursor पहली row से पहले शुरू होता है और यह एक exception फेंकता है। - column index
0का उपयोग करना, जबकि JDBC column और parameter indexes1से शुरू होते हैं। Connection,StatementऔरResultSetको close न करना (उदाहरण के लिए try-with-resources से), जो database resources leak करता है।
Chapter Quiz — Complete all 4 topics to unlock
0/4 topics done
Complete these topics first: