Reuse and reprepare a parameterized query¶
Keep one MySQL session open throughout this recipe. Prepare a parameterized lookup, execute it with two IDs, then deallocate it before changing the table. A new prepare picks up the current schema.
CREATE DATABASE cookbook_prepare;
CREATE TABLE cookbook_prepare.orders(id INT PRIMARY KEY, amount INT);
INSERT INTO cookbook_prepare.orders VALUES(1,10),(2,20);
PREPARE order_lookup FROM 'SELECT amount FROM cookbook_prepare.orders WHERE id=?';
SET @order_id=1;
EXECUTE order_lookup USING @order_id;
SET @order_id=2;
EXECUTE order_lookup USING @order_id;
DEALLOCATE PREPARE order_lookup;
ALTER TABLE cookbook_prepare.orders ADD COLUMN reviewed INT DEFAULT 0;
PREPARE order_lookup FROM
'SELECT amount,reviewed FROM cookbook_prepare.orders WHERE id=?';
EXECUTE order_lookup USING @order_id;
DEALLOCATE PREPARE order_lookup;
DROP DATABASE cookbook_prepare;
The first two lookups return amounts 10 and 20; after the schema change, the new statement returns 20 and the default reviewed=0. Always deallocate statements the application no longer uses. See the v4.2.4 source test.