Feedback Form

Core SQL Operations via JDBC: SELECT, INSERT, UPDATE, DELETE with PreparedStatement

Core SQL Operations via JDBC: SELECT, INSERT, UPDATE, DELETE with PreparedStatement

जब हम Java language में Database के साथ काम करते हैं, तो JDBC (Java Database Connectivity) का use किया जाता है। JDBC एक ऐसा powerful API है जो हमें Database से connect करने, data retrieve करने और modify करने की सुविधा देता है। इस blog में हम Core SQL Operations — यानी SELECT, INSERT, UPDATE, और DELETE को PreparedStatement के साथ समझेंगे। यह topic college exams में बहुत important होता है और practically भी हर developer के काम आता है।

What is PreparedStatement?

PreparedStatement, JDBC interface का एक advanced version है जो SQL queries को precompile करता है और runtime errors को कम करता है। यह normal Statement की तुलना में ज़्यादा secure और fast होता है क्योंकि यह SQL injection से बचाता है।

PreparedStatement का use तब किया जाता है जब हमें same SQL query को बार-बार execute करना हो, लेकिन हर बार different data के साथ। उदाहरण के लिए — जब हमें multiple records insert करने हों या किसी specific data को update/delete करना हो।

Advantages of PreparedStatement

  • SQL injection attacks से protection देता है।
  • Query execution speed बढ़ाता है।
  • Code को readable और maintainable बनाता है।
  • Dynamic parameters को आसानी से handle करता है।

Database Connection Setup

PreparedStatement का use करने से पहले हमें Database connection establish करना होता है। नीचे basic steps दिए गए हैं:

Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/studentdb", "root", "password");

ऊपर के code से Java program MySQL database से connect हो जाएगा। अब हम PreparedStatement का use करके core SQL operations perform करेंगे।

1. SELECT Operation using PreparedStatement

SELECT statement का use database से data retrieve करने के लिए किया जाता है। PreparedStatement में हम query को precompile करते हैं और parameters को runtime पर set करते हैं।

Example Code:

String sql = "SELECT * FROM students WHERE id = ?";
PreparedStatement ps = con.prepareStatement(sql);
ps.setInt(1, 101);
ResultSet rs = ps.executeQuery();
while(rs.next()) {
  System.out.println(rs.getInt("id") + " " + rs.getString("name"));
}

ऊपर के code में “?” parameter placeholder है, जहाँ पर हमने student ID pass की है। PreparedStatement इस query को compile करके efficient तरीके से data fetch करता है।

Key Points:

  • executeQuery() का use SELECT statements के लिए होता है।
  • ResultSet object database से fetched rows को represent करता है।
  • हम rs.next() से row-by-row data access करते हैं।

2. INSERT Operation using PreparedStatement

INSERT statement का use database में new records जोड़ने के लिए किया जाता है। PreparedStatement के साथ हम query को dynamic बना सकते हैं।

Example Code:

String sql = "INSERT INTO students (id, name, course) VALUES (?, ?, ?)";
PreparedStatement ps = con.prepareStatement(sql);
ps.setInt(1, 105);
ps.setString(2, "Amit Kumar");
ps.setString(3, "MCA");
int rows = ps.executeUpdate();
System.out.println(rows + " record inserted successfully!");

यहाँ executeUpdate() method का use किया गया है क्योंकि हम data को modify (insert) कर रहे हैं। अगर record successfully insert हो जाता है, तो यह method affected rows की count return करता है।

Key Points:

  • executeUpdate() insert, update, और delete operations के लिए use किया जाता है।
  • Parameters को “?” placeholders में sequentially set किया जाता है।
  • PreparedStatement database operations को efficient और safe बनाता है।

3. UPDATE Operation using PreparedStatement

UPDATE statement का use existing records को modify करने के लिए किया जाता है। PreparedStatement का use करने से हम केवल targeted records को update कर सकते हैं।

Example Code:

String sql = "UPDATE students SET course = ? WHERE id = ?";
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, "MCA");
ps.setInt(2, 105);
int rows = ps.executeUpdate();
System.out.println(rows + " record updated successfully!");

ऊपर के example में हमने student की course information update की है। यह query केवल उस record को modify करेगी जिसका id = 105 है।

Best Practices:

  • Always check return value of executeUpdate() to ensure successful operation।
  • Database transaction को manage करने के लिए auto-commit mode को handle करें।
  • try-with-resources का use करें ताकि resources properly close हों।

4. DELETE Operation using PreparedStatement

DELETE statement का use किसी existing record को remove करने के लिए किया जाता है। PreparedStatement इसे secure और error-free बनाता है।

Example Code:

String sql = "DELETE FROM students WHERE id = ?";
PreparedStatement ps = con.prepareStatement(sql);
ps.setInt(1, 105);
int rows = ps.executeUpdate();
System.out.println(rows + " record deleted successfully!");

यह code उस student का record delete कर देगा जिसकी ID 105 है। हमेशा यह सुनिश्चित करें कि WHERE clause दिया गया हो, वरना पूरी table का data delete हो सकता है।

Key Notes:

  • DELETE statement बिना WHERE clause के dangerous हो सकता है।
  • Transaction rollback mechanism implement करें ताकि accidental deletions recover हो सकें।
  • PreparedStatement SQL injection से बचाव करता है।

Batch Processing using PreparedStatement

जब हमें multiple records को एक साथ insert या update करना हो, तो batch processing का use किया जाता है। PreparedStatement में addBatch() और executeBatch() methods available होते हैं।

Example:

String sql = "INSERT INTO students (id, name, course) VALUES (?, ?, ?)";
PreparedStatement ps = con.prepareStatement(sql);

ps.setInt(1, 201);
ps.setString(2, "Ravi");
ps.setString(3, "B.Tech");
ps.addBatch();

ps.setInt(1, 202);
ps.setString(2, "Neha");
ps.setString(3, "MBA");
ps.addBatch();

int[] result = ps.executeBatch();
System.out.println("Batch executed: " + result.length + " records inserted.");

Batch processing performance improve करती है क्योंकि यह multiple SQL queries को एक साथ database पर execute करती है।

PreparedStatement vs Statement

Feature Statement PreparedStatement
Execution Type Query हर बार compile होती है Query precompiled होती है
Security SQL Injection का खतरा SQL Injection से सुरक्षित
Performance Slow Faster execution
Reusability कम reusability High reusability
Dynamic Parameters Manually manage करने पड़ते हैं “?” placeholders से manage होते हैं

Handling Transactions in JDBC

Transaction handling database operations को atomic और consistent बनाता है। JDBC में हम commit() और rollback() methods का use करके transactions control कर सकते हैं।

Example Code:

con.setAutoCommit(false);
PreparedStatement ps1 = con.prepareStatement("UPDATE accounts SET balance = balance - ? WHERE acc_no = ?");
PreparedStatement ps2 = con.prepareStatement("UPDATE accounts SET balance = balance + ? WHERE acc_no = ?");

ps1.setDouble(1, 1000);
ps1.setInt(2, 101);
ps1.executeUpdate();

ps2.setDouble(1, 1000);
ps2.setInt(2, 102);
ps2.executeUpdate();

con.commit();
System.out.println("Transaction Successful!");

अगर बीच में कोई error आता है तो rollback() method का use करके पूरी transaction को revert किया जा सकता है।

Important Points to Remember

  • Always close ResultSet, PreparedStatement और Connection objects।
  • Use try-with-resources for automatic resource management।
  • Database credentials को secure location (जैसे properties file) में रखें।
  • Logging enable करें ताकि database activities trace की जा सकें।
  • Query optimization और indexing से performance improve करें।

Real-Life Example: Student Management System

एक small example लेते हैं जहाँ हम student management system में CRUD operations perform करते हैं:

public class StudentDAO {
  Connection con;

  public StudentDAO() throws Exception {
    Class.forName("com.mysql.cj.jdbc.Driver");
    con = DriverManager.getConnection("jdbc:mysql://localhost:3306/studentdb", "root", "password");
  }

  public void insertStudent(int id, String name, String course) throws Exception {
    PreparedStatement ps = con.prepareStatement("INSERT INTO students VALUES (?, ?, ?)");
    ps.setInt(1, id);
    ps.setString(2, name);
    ps.setString(3, course);
    ps.executeUpdate();
    System.out.println("Student inserted successfully!");
  }

  public void getStudent(int id) throws Exception {
    PreparedStatement ps = con.prepareStatement("SELECT * FROM students WHERE id = ?");
    ps.setInt(1, id);
    ResultSet rs = ps.executeQuery();
    if(rs.next()) {
      System.out.println(rs.getInt("id") + " - " + rs.getString("name") + " - " + rs.getString("course"));
    } else {
      System.out.println("No student found!");
    }
  }
}

इस तरह PreparedStatement के use से JDBC programs secure, fast और efficient बनते हैं। यह practically हर database-driven Java project का core हिस्सा है।