Feedback Form

Introduction to SQL in Java: Embedding Queries in JDBC Applications

Introduction to SQL in Java: Embedding Queries in JDBC Applications

अगर आप Java language में Database से connect होकर data को access या modify करना चाहते हैं, तो आपको SQL और JDBC दोनों की basic understanding होनी चाहिए। आज के इस blog में हम step-by-step समझेंगे कि SQL को Java में कैसे embed किया जाता है, यानी कैसे Java program के अंदर SQL queries run कर सकते हैं using JDBC (Java Database Connectivity) API। यह topic न सिर्फ college exams के लिए important है बल्कि practical development में भी बहुत useful है।

What is SQL in Java?

SQL (Structured Query Language) एक standard language है जो database से data retrieve या manipulate करने के लिए use होती है। जब हम Java program में SQL queries embed करते हैं, तो हम database से directly interact कर सकते हैं — जैसे records fetch करना, insert करना, update या delete करना। Java के अंदर SQL को use करने का सबसे popular तरीका है JDBC API का use।

Example:

String query = "SELECT * FROM students WHERE marks > 75";

ऊपर दी गई query को Java के JDBC code में embed करके run किया जा सकता है ताकि high-scoring students की list database से fetch की जा सके।

Understanding JDBC (Java Database Connectivity)

JDBC एक API (Application Programming Interface) है जो Java programs को databases से communicate करने की सुविधा देता है। इसे Sun Microsystems (अब Oracle) ने develop किया था ताकि Java applications किसी भी relational database जैसे MySQL, Oracle, PostgreSQL, SQL Server आदि के साथ easily connect हो सकें।

JDBC के मुख्य Components:

  • DriverManager: Database driver को load और manage करता है।
  • Connection: Java application और database के बीच connection establish करता है।
  • Statement: SQL query को database पर execute करता है।
  • ResultSet: Query से मिले results को hold करता है।

Steps to Embed SQL in Java Program

अब चलिए step-by-step देखते हैं कि कैसे Java code में SQL queries को embed करके database operations perform किए जाते हैं।

Step 1: Load JDBC Driver

हर database के लिए अलग driver होता है। Driver को load करने के लिए हम Class.forName() method का use करते हैं।

Class.forName("com.mysql.cj.jdbc.Driver");

यह line MySQL JDBC driver को load करती है ताकि Java program MySQL database से connect हो सके।

Step 2: Establish Connection

अब हमें database से connection establish करना होगा। इसके लिए DriverManager.getConnection() method का use करते हैं।

Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/college", "root", "password");

यह connection object “college” नाम के database से connection बना देता है।

Step 3: Create Statement Object

अब SQL query को execute करने के लिए Statement object create करते हैं।

Statement stmt = con.createStatement();

Step 4: Execute SQL Query

Query execute करने के दो तरीके होते हैं — executeQuery() (for SELECT queries) और executeUpdate() (for INSERT, UPDATE, DELETE)।

ResultSet rs = stmt.executeQuery("SELECT * FROM students");

यह query students table के सभी records को fetch करती है।

Step 5: Process the Result

अब result को process करने के लिए ResultSet object का use किया जाता है।

while(rs.next()) { System.out.println(rs.getInt("id") + " " + rs.getString("name")); }

यह code हर student का id और name print करता है।

Step 6: Close the Connection

Work complete होने के बाद connection को close करना जरूरी है ताकि memory leak न हो।

con.close();

Types of Statements in JDBC

JDBC तीन प्रकार के statements provide करता है जो SQL queries को execute करने के लिए use होते हैं।

TypeDescription
StatementSimple SQL queries के लिए use होता है जो बार-बार नहीं चलतीं।
PreparedStatementPrecompiled SQL queries के लिए use होता है, जिससे performance बेहतर होती है।
CallableStatementStored procedures को call करने के लिए use किया जाता है।

PreparedStatement in Detail

PreparedStatement SQL injection से बचने और performance improve करने का best तरीका है। इसमें query पहले से compile होती है और parameters को dynamically set किया जा सकता है।

Example:

PreparedStatement ps = con.prepareStatement("INSERT INTO students VALUES (?, ?, ?)"); ps.setInt(1, 101); ps.setString(2, "Amit"); ps.setInt(3, 85); ps.executeUpdate();

इस method में “?” placeholders होते हैं जिन्हें runtime पर actual values से replace किया जाता है।

Using SELECT Query in JDBC

SELECT query का use data fetch करने के लिए होता है। Example नीचे दिया गया है:

String sql = "SELECT * FROM students WHERE marks > ?"; PreparedStatement ps = con.prepareStatement(sql); ps.setInt(1, 60); ResultSet rs = ps.executeQuery();

यह query उन students की list लाएगी जिनके marks 60 से अधिक हैं।

Inserting Data Using JDBC

Insert query का use नए records को database में add करने के लिए होता है।

String query = "INSERT INTO students VALUES (105, 'Neha', 78)"; stmt.executeUpdate(query);

Updating Data Using JDBC

Update query existing data को modify करने के लिए use की जाती है।

String query = "UPDATE students SET marks = 90 WHERE id = 101"; stmt.executeUpdate(query);

Deleting Data Using JDBC

Delete query का use किसी particular record को remove करने के लिए किया जाता है।

String query = "DELETE FROM students WHERE id = 102"; stmt.executeUpdate(query);

Handling SQL Exceptions

SQL queries execute करते समय error आने की संभावना रहती है, जैसे wrong query, missing table या database connection failure। ऐसे में SQLException को handle करना जरूरी है।

try { // Database code } catch (SQLException e) { System.out.println("Error: " + e.getMessage()); }

Advantages of Embedding SQL in Java

  • Java application और database के बीच seamless integration।
  • Dynamic data access — data को real-time में modify किया जा सकता है।
  • SQL injection से सुरक्षा (PreparedStatement के जरिए)।
  • Platform independent solution।
  • Database operations automation और performance optimization।

Real-Life Example: Student Management System

मान लीजिए कि आपके पास एक Student Management System है, जहाँ आपको student details add, update या delete करनी होती हैं। JDBC और SQL के combination से आप यह पूरा system आसानी से बना सकते हैं।

Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/college", "root", "pass"); PreparedStatement ps = con.prepareStatement("SELECT * FROM students WHERE marks > ?"); ps.setInt(1, 75); ResultSet rs = ps.executeQuery(); while(rs.next()) { System.out.println(rs.getString("name") + " - " + rs.getInt("marks")); }

Best Practices for Embedding SQL in Java

  • Always close ResultSet, Statement और Connection objects।
  • Use PreparedStatement instead of Statement for security।
  • Database credentials को hard-code न करें — external file या environment variables में रखें।
  • Transactions use करें जब multiple queries dependent हों।
  • Exception handling हमेशा include करें।

Important Keywords and Concepts

TermMeaning
JDBCJava Database Connectivity API
SQLStructured Query Language
ConnectionDatabase link between Java and DB
StatementSQL command executor
ResultSetHolds the fetched data
DriverManagerManages DB drivers

Exam Specific Notes

  • JDBC full form: Java Database Connectivity।
  • PreparedStatement is used for parameterized queries।
  • executeQuery() → SELECT queries; executeUpdate() → INSERT/UPDATE/DELETE।
  • ResultSet object read-only और forward-only होता है by default।
  • DriverManager.getConnection() से connection establish होता है।
  • Always close database connection using con.close()।

Quick Revision Notes

  • SQL को Java में embed करने का तरीका है JDBC API।
  • Steps: Load Driver → Connect → Create Statement → Execute Query → Process Result → Close Connection।
  • PreparedStatement SQL injection से protect करता है।
  • JDBC universal database access प्रदान करता है।
  • Exam में अक्सर code-based question पूछे जाते हैं जैसे “Write a JDBC program to insert data into table।”