Java-এ PreparedStatement ব্যবহার করে টেবিলে রেকর্ড ইনসার্ট করার সিনট্যাক্স:
String query = "INSERT INTO yourTableName(yourColumnName1, yourColumnName2, yourColumnName3, ... )"
+ "VALUES (?, ?, ?, ... )";
PreparedStatement অবজেক্ট ব্যবহার করে কলামের ভ্যালু সেট করা:
PreparedStatement pstmt = con.prepareStatement(query); pstmt.setXXX(1, yourValue); pstmt.setXXX(2, yourValue); pstmt.setXXX(3, yourValue); ... pstmt.executeUpdate();
সম্পূর্ণ উদাহরণ
টেবিল তৈরি:
mysql> CREATE TABLE CourseDemo (
CourseId INT,
StudentName VARCHAR(20),
CourseName VARCHAR(30)
);
Java কোড:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.Scanner;
public class InsertRecordInPreparedStatement {
static int cid;
static String studentName;
static String courseName;
public static void main(String[] args) {
String JdbcURL = "jdbc:mysql://localhost:3306/sample?useSSL=false";
String Username = "root";
String password = "123456";
Connection con = null;
Scanner keyboardInput = new Scanner(System.in);
PreparedStatement pstmt = null;
String query = "INSERT INTO CourseDemo(CourseId, StudentName, CourseName) VALUES (?, ?, ?)";
try {
con = DriverManager.getConnection(JdbcURL, Username, password);
input(keyboardInput);
pstmt = con.prepareStatement(query);
pstmt.setInt(1, cid);
pstmt.setString(2, studentName);
pstmt.setString(3, courseName);
int status = pstmt.executeUpdate();
if (status > 0) {
System.out.println("Record is inserted successfully !!!");
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void input(Scanner keyboardInput) {
System.out.println("Enter the course id:");
cid = keyboardInput.nextInt();
System.out.println("Enter the Student Name:");
studentName = keyboardInput.next();
System.out.println("Enter the Course Name:");
courseName = keyboardInput.next();
}
}
আউটপুট:
Enter the course id: 101 Enter the Student Name: John Enter the Course Name: Java Record is inserted successfully !!!
MySQL-এ যাচাই:
mysql> SELECT * FROM CourseDemo; +----------+-------------+------------+ | CourseId | StudentName | CourseName | +----------+-------------+------------+ | 101 | John | Java | +----------+-------------+------------+