← Back to Advanced Java Course | Chapter 8: Database & JPA | Lesson 1 of 4

Java JDBC परिचय

JDBC वह तरीका है जिससे Java किसी database से बात करता है, जैसे एक विशाल filing cabinet तक phone line। आप connect होते हैं, सवाल भेजते हैं और जवाब पढ़ते हैं।
Syntax
java
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

java
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");
		}
	}
}

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

java
// 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");
	}
}

Retrieving ResultSet

एक ResultSet object किसी query से return हुए tabular data पर एक cursor को represent करता है। आप हर row के columns निकालने के लिए इसके typed getter methods (getString, getInt, वगैरह) call करते हैं, next() के false return करने तक अगली row पर बढ़ते हुए।

उदाहरण: Retrieving ResultSet

java
// 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"));
		}
	}
}

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

java
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);
	}
}

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

java
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
	}
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. पहले next() call किए बिना किसी ResultSet से पढ़ना, क्योंकि cursor पहली row से पहले शुरू होता है और यह एक exception फेंकता है।
  2. column index 0 का उपयोग करना, जबकि JDBC column और parameter indexes 1 से शुरू होते हैं।
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.