預編譯一次肉津,可以多次執(zhí)行。用來解決一條SQL語句頻繁執(zhí)行的問題偶洋。
預處理語句:prepare 預處理名字 from ‘sql語句’
執(zhí)行預處理:execute 預處理名字 [using 變量]
例題一:
mysql> prepare stmt from 'select * from stuinfo'; # 創(chuàng)建預處理
Query OK, 0 rows affected (0.00 sec)
Statement prepared
mysql> execute stmt; # 執(zhí)行預處理
+--------+----------+--------+--------+---------+------------+
| stuNo | stuName | stuSex | stuAge | stuSeat | stuAddress |
+--------+----------+--------+--------+---------+------------+
| s25301 | 張秋麗 | 男 | 18 | 1 | 北京 |
| s25302 | 李文才 | 男 | 31 | 3 | 上海 |
| s25303 | 李斯文 | 女 | 22 | 2 | 北京 |
| s25304 | 歐陽俊雄 | 男 | 28 | 4 | 天津 |
| s25305 | 諸葛麗麗 | 女 | 23 | 7 | 河南 |
| s25318 | 爭青小子 | 男 | 26 | 6 | 天津 |
| s25319 | 梅超風 | 女 | 23 | 5 | 河北 |
+--------+----------+--------+--------+---------+------------+
7 rows in set (0.00 sec)
例題二:傳遞參數(shù)
mysql> delimiter //
mysql> prepare stmt from 'select * from stuinfo where stuno=?' // -- ?是位置占位符
Query OK, 0 rows affected (0.00 sec)
Statement prepared
mysql> set @id='s25301'; -- 變量以@開頭玄窝,通過set給變量賦值
-> execute stmt using @id // -- 執(zhí)行預處理悍引,傳遞參數(shù)
Query OK, 0 rows affected (0.00 sec)
+--------+---------+--------+--------+---------+------------+
| stuNo | stuName | stuSex | stuAge | stuSeat | stuAddress |
+--------+---------+--------+--------+---------+------------+
| s25301 | 張秋麗 | 男 | 18 | 1 | 北京 |
+--------+---------+--------+--------+---------+------------+
1 row in set (0.00 sec)
腳下留心:
1、?是位置占位符
2俩块、變量以@開頭
3浓领、通過set給變量賦值
例題三:傳遞多個參數(shù)
mysql> prepare stmt from 'select * from stuinfo where stusex=? and stuaddress=?' //
Query OK, 0 rows affected (0.00 sec)
Statement prepared
mysql> set @sex='男';
-> set @addr='北京';
-> execute stmt using @sex,@addr //
Query OK, 0 rows affected (0.00 sec)
Query OK, 0 rows affected (0.00 sec)
+--------+---------+--------+--------+---------+------------+
| stuNo | stuName | stuSex | stuAge | stuSeat | stuAddress |
+--------+---------+--------+--------+---------+------------+
| s25301 | 張秋麗 | 男 | 18 | 1 | 北京 |
+--------+---------+--------+--------+---------+------------+
1 row in set (0.00 sec)