สร้างตารางและ INSERT ด้วย Prepared Statements
1. สร้างตาราง (CREATE TABLE):
mysql> PREPARE stmt3 FROM 'CREATE TABLE Student(Id INT, Name Varchar(20))'; Query OK, 0 rows affected (0.00 sec) Statement prepared mysql> EXECUTE stmt3; Query OK, 0 rows affected (0.73 sec) mysql> DEALLOCATE PREPARE stmt3; Query OK, 0 rows affected (0.00 sec)
2. แทรกข้อมูล (INSERT) หลายแถว:
mysql> PREPARE stmt7 FROM 'INSERT INTO Student(Id,Name) values(?,?)'; Query OK, 0 rows affected (0.00 sec) Statement prepared mysql> SET @A = 1, @B = 'Ram'; mysql> EXECUTE stmt7 using @A, @B; Query OK, 1 row affected (0.04 sec) mysql> SET @A = 2, @B = 'Shyam'; mysql> EXECUTE stmt7 using @A, @B; Query OK, 1 row affected (0.08 sec) mysql> SET @A = 3, @B = 'Mohan'; mysql> EXECUTE stmt7 using @A, @B; Query OK, 1 row affected (0.04 sec) mysql> Select * from Student; +------+-------+ | Id | Name | +------+-------+ | 1 | Ram | | 2 | Shyam | | 3 | Mohan | +------+-------+
ใช้ prepared statement เดียว (stmt7) แทรกข้อมูลหลายครั้งด้วยค่าต่างกันได้