EXPERIMENT -05
WRITE A JDBC CODE FOR PREPARED STATEMENTS, SCROLLABLE AND
UPDATABLE RESULT
Assumptions
• Database: MySQL
• Database name: studentdb
• Table name: student
Create database studentdb;
Use studentdb;
Create table shyam(id INT PRIMARY KEY, name VARCHAR(50), marks INT);
JDBC Program
PreparedStatement + Scrollable & Updatable ResultSet
import [Link];
import [Link];
import
[Link];
import [Link]; import
[Link];
public class JDBCPreparedScrollableUpdatable
{ public static void main(String[] args) { try {
// 1. Load JDBC Driver
[Link]("[Link]");
// 2. Establish Connection
Connection con = [Link](
"jdbc:mysql://localhost:3306/studentdb",
"root",
"password"
);
// ---------------- PreparedStatement (INSERT) ----------------
String insertSQL =
"INSERT INTO shyam(id, name, marks) VALUES (?, ?, ?)"; PreparedStatement
ps = [Link](insertSQL);
[Link](1, 102);
[Link](2,
"Rahul"); [Link](3,
90);
[Link]();
[Link]("Record inserted using PreparedStatement");
// ---------------- Scrollable & Updatable ResultSet ----------------
Statement stmt = [Link](
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE
);
ResultSet rs = [Link]("SELECT * FROM student");
// Move to last record
[Link]();
[Link]("Last Record: "
+ [Link](1) + " " +
[Link](2) + " " +
[Link](3));
// Move to first record
[Link]();
// Update record
[Link]("marks",
95); [Link]();
[Link]("Record updated using Updatable ResultSet");
// Insert new record using
ResultSet [Link]();
[Link]("id", 103);
[Link]("name", "Amit");
[Link]("marks", 88);
[Link]();
[Link]("Record inserted using ResultSet");
// Close connection
[Link]();
} catch (Exception e) {
[Link](e);
}
}
}
Sample Output
Record inserted using PreparedStatement
Last Record: 102 Rahul 90
Record updated using Updatable ResultSet
Record inserted using ResultSet
• PreparedStatement improves performance and prevents SQL injection.
• Scrollable ResultSet allows moving forward/backward (first(), last()).
• Updatable ResultSet allows updating database records directly using
ResultSet.
• TYPE_SCROLL_INSENSITIVE allows scrolling without reflecting DB changes.
• CONCUR_UPDATABLE enables record modification.
Important Methods to Remember
Method Purpose
setInt(), setString() Set values in PreparedStatement
first(), last() Scroll ResultSet
updateRow() Update current row
insertRow() Insert new row