Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MySQL

เพิ่มข้อมูลใน MySQL ด้วย PreparedStatement ใน Java


ใช้ PreparedStatement ใน Java เพื่อ INSERT ข้อมูลอย่างปลอดภัย (ป้องกัน SQL Injection)

รูปแบบไวยากรณ์

String query = "INSERT INTO yourTableName(col1, col2, col3) VALUES (?, ?, ?)"; 
PreparedStatement pstmt = con.prepareStatement(query); 
pstmt.setXXX(1, value1); 
pstmt.setXXX(2, value2); 
pstmt.setXXX(3, value3); 
pstmt.executeUpdate();

ตัวอย่างโค้ด Java สมบูรณ์

import java.sql.*;
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";
        
        try (Connection con = DriverManager.getConnection(jdbcURL, username, password);
             Scanner scanner = new Scanner(System.in)) {
            
            String query = "INSERT INTO CourseDemo(CourseId, StudentName, CourseName) VALUES (?, ?, ?)";
            PreparedStatement pstmt = con.prepareStatement(query);
            
            input(scanner);
            
            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();
        }
    }
    
    static void input(Scanner scanner) {
        System.out.print("Enter the course id: "); cid = scanner.nextInt();
        System.out.print("Enter the Student Name: "); studentName = scanner.next();
        System.out.print("Enter the Course Name: "); courseName = scanner.next();
    }
}

สร้างตารางใน MySQL

mysql> CREATE TABLE CourseDemo ( CourseId INT, StudentName VARCHAR(20), CourseName VARCHAR(30) );

ผลลัพธ์ตัวอย่าง

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       | +----------+-------------+------------+

ข้อดีของ PreparedStatement: ป้องกัน SQL Injection, ใช้งานซ้ำได้ (Reusable), ประสิทธิภาพดีกว่า Statement ธรรมดา