Prepared

MatrixOne provides support for server-side prepared statements. This support takes advantage of the efficient client/server binary protocol. Using prepared statements with placeholders for parameter values has the following benefits:

Less overhead for parsing the statement each time it is executed. Typically, database applications process large volumes of almost-identical statements, with only changes to literal or variable values in clauses such as WHERE for queries and deletes, SET for updates, and VALUES for inserts.

Protection against SQL injection attacks. The parameter values can contain unescaped SQL quote and delimiter characters.

PREPARE, EXECUTE, and DEALLOCATE PREPARE Statements

SQL syntax for prepared statements is based on three SQL statements:

Create a prepared statement

  1. PREPARE stmt_name FROM preparable_stmt
ArgumentsDescription
stmt_nameThe name of the prepared statement.
preparable_stmta string literal or a user variable that contains the text of the SQL statement. The text must represent a single statement, not multiple statements.

Executes a prepared statement

  1. EXECUTE stmt_name [USING @var_name [, @var_name] ...]
ArgumentsDescription
stmt_nameThe name of the prepared statement.

Delete a prepared statement

  1. {DEALLOCATE | DROP} PREPARE stmt_name
ArgumentsDescription
stmt_nameThe name of the prepared statement.

Example

  1. -- Create table
  2. CREATE TABLE customers (
  3. id INT PRIMARY KEY,
  4. name VARCHAR(50),
  5. email VARCHAR(50)
  6. );
  7. -- Insert data
  8. INSERT INTO customers (id, name, email)
  9. VALUES (1, 'John Doe', 'john@example.com'),
  10. (2, 'Jane Smith', 'jane@example.com'),
  11. (3, 'Mike Johnson', 'mike@example.com');
  12. -- Prepare statement
  13. mysql> PREPARE stmt FROM 'SELECT * FROM customers WHERE id = ?';
  14. Query OK, 0 rows affected (0.02 sec)
  15. -- Execute prepared statement
  16. mysql> SET @id = 2;
  17. Query OK, 0 rows affected (0.00 sec)
  18. mysql> EXECUTE stmt USING @id;
  19. +------+------------+------------------+
  20. | id | name | email |
  21. +------+------------+------------------+
  22. | 2 | Jane Smith | jane@example.com |
  23. +------+------------+------------------+
  24. 1 row in set (0.01 sec)
  25. -- Deallocate statement
  26. mysql> DEALLOCATE PREPARE stmt;
  27. Query OK, 0 rows affected (0.00 sec)

The above example begins by creating a table named customers with three columns: id, name, and email. Next, three rows of data are inserted into the table.

Then, the PREPARE statement is used to prepare a statement, and the SELECT * FROM customers WHERE id = ? query is stored in the stmt variable.

When executing the prepared statement, the @id variable is set to 2, and the EXECUTE statement is used to execute the prepared statement with the @id parameter.

Finally, the DEALLOCATE PREPARE statement is used to deallocate the prepared statement and free up the associated resources.