Overview
Scenarios
Product Architecture
Instance Types
Compatibility Notes
Usage specification recommendations
PREPARE statement to create a prepared statement. In the SQL template, the English half-width question mark ? is used as a parameter placeholder.PREPARE stmt_name FROM preparable_stmt;
Parameter | Description |
stmt_name | The name of the prepared statement, used for subsequent references to this statement. The name must be unique within the current session and is case-insensitive. |
preparable_stmt | The SQL statement template, which can be a string literal or a user variable. Use ? as a parameter placeholder. |
id:PREPARE stmt_query FROM 'SELECT * FROM employees WHERE id = ?';
SET @sql = 'SELECT * FROM employees WHERE id = ?';PREPARE stmt_query FROM @sql;
EXECUTE statement to execute the created prepared statement, and pass parameter values via the USING clause. Parameter values must be passed through user variables.EXECUTE stmt_name [USING @var_name [, @var_name] ...];
Parameter | Description |
stmt_name | The name of the prepared statement to be executed, which must be a statement already created via PREPARE |
@var_name | User variables used to pass parameter values to the prepared statement. The number of variables must match the number of ? placeholders in the SQL template. |
id being 1:SET @id = 1;EXECUTE stmt_query USING @id;
+----+----------+------------+--------+| id | name | department | salary |+----+----------+------------+--------+| 1 | Zhang San| R&D | 15000 |+----+----------+------------+--------+1 row in set (0.00 sec)
SET @id = 2;EXECUTE stmt_query USING @id;
DEALLOCATE PREPARE statement to release created prepared statements and reclaim server resources.{DEALLOCATE | DROP} PREPARE stmt_name;
Parameter | Description |
stmt_name | The name of the prepared statement to be released |
DEALLOCATE PREPARE stmt_query;
DEALLOCATE PREPARE to release resources after using prepared statements, avoiding occupying server memory.id in the books table.PREPARE stmt_select_book FROM 'SELECT * FROM books WHERE id = ?';
SET @book_id = 1;EXECUTE stmt_select_book USING @book_id;
SET @book_id = 5;EXECUTE stmt_select_book USING @book_id;
DEALLOCATE PREPARE stmt_select_book;
books table.PREPARE stmt_insert_book FROM 'INSERT INTO books (title, type, stock, price, published_at) VALUES (?, ?, ?, ?, ?)';
SET @title = 'TDSQL Boundless Practical Guide';SET @type = 'Technology';SET @stock = 100;SET @price = 89.00;SET @published_at = '2026-01-01';EXECUTE stmt_insert_book USING @title, @type, @stock, @price, @published_at;
DEALLOCATE PREPARE stmt_insert_book;
books table.PREPARE stmt_update_stock FROM 'UPDATE books SET stock = ? WHERE id = ?';
SET @new_stock = 200;SET @book_id = 1;EXECUTE stmt_update_stock USING @new_stock, @book_id;
DEALLOCATE PREPARE stmt_update_stock;
id in the books table.PREPARE stmt_delete_book FROM 'DELETE FROM books WHERE id = ?';
SET @book_id = 10;EXECUTE stmt_delete_book USING @book_id;
DEALLOCATE PREPARE stmt_delete_book;
-- Dynamically construct a query statementSET @query_str = 'SELECT COUNT(*) INTO @result FROM performance_schema.session_variables WHERE VARIABLE_NAME = ?';PREPARE stmt_check FROM @query_str;-- Set parameters and executeSET @var_name = 'rocksdb_bulk_load';EXECUTE stmt_check USING @var_name;-- View the resultsSELECT @result;-- Release the statementDEALLOCATE PREPARE stmt_check;
mysqldump tool uses a similar PREPARE...FROM @variable approach to dynamically construct SQL statements during data export, which is used to detect whether the target server supports a specific storage engine feature.SELECTINSERTUPDATEDELETEREPLACECALLDOCREATE DATABASE,CREATE TABLE,CREATE TEMPORARY TABLE,CREATE INDEX,CREATE USERDROP DATABASE,DROP TABLE,DROP TEMPORARY TABLE,DROP INDEX,DROP USER,DROP VIEWALTER USERRENAME TABLE,RENAME USERTRUNCATE TABLEANALYZE TABLE,CHECKSUM TABLE,OPTIMIZE TABLE,REPAIR TABLEGRANT,REVOKE ALL PRIVILEGESSHOW CREATE TABLE,SHOW CREATE PROCEDURE,SHOW CREATE FUNCTION,SHOW CREATE VIEW,SHOW CREATE EVENTSHOW BINLOG EVENTS,SHOW MASTER STATUS,SHOW BINARY LOGS,SHOW SLAVE STATUSINSTALL PLUGIN,UNINSTALL PLUGINKILLCOMMITSET OPTIONRESET MASTER,RESET SLAVESLAVE START,SLAVE STOPLOAD DATA INFILE, USE, BEGIN, and so on) are not supported for execution via prepared statements.mysql_stmt_init() to initialize the prepared statement handle.mysql_stmt_prepare() to send the SQL template to the server for preprocessing.mysql_stmt_bind_param() to bind parameter values.mysql_stmt_execute() to execute the prepared statement.mysql_stmt_bind_result() and mysql_stmt_fetch() to obtain query results (applicable only to query statements).mysql_stmt_close() to close the statement handle and release resources.Function | Description |
mysql_stmt_init() | Initialize a MYSQL_STMT handle for subsequent prepared statement operations. |
mysql_stmt_prepare() | Send the SQL statement template to the server for parsing and compilation. |
mysql_stmt_bind_param() | Bind variables in the application to the ? placeholder in the SQL template. |
mysql_stmt_execute() | Execute the prepared statement. |
mysql_stmt_store_result() | Fetch the complete result set from the server to the client cache. |
mysql_stmt_result_metadata() | Obtain metadata information (column names, types, and so on) for the results returned by prepared statements. |
mysql_stmt_fetch() | Fetch result set data row by row. |
mysql_stmt_close() | Close the prepared statement handle to release client-side and server-side resources. |
mysql_stmt_errno() | Return the error code for the most recent operation performed on the prepared statement. |
mysql_stmt_error() | Return the error message for the most recent operation performed on the prepared statement. |
mysql_stmt_attr_set() | Set statement attributes, such as cursor type CURSOR_TYPE_READ_ONLY. |
mysql_stmt_next_result() | Used to handle multiple result set scenarios; obtain the next result set. |
STMT_ATTR_CURSOR_TYPE to CURSOR_TYPE_READ_ONLY, the read-only cursor mode can be enabled. In this mode, the result set will not be loaded in full into client memory but fetched row by row on demand, making it suitable for handling queries with large datasets.Programming languages | Driver or framework | Prepared Statements API |
Java | JDBC | java.sql.PreparedStatement |
Python | MySQL Connector/Python | cursor.execute(sql, params) |
Go | go-sql-driver/mysql | db.Prepare() + stmt.Exec() |
PHP | PDO | PDO::prepare() + PDOStatement::execute() |
Node.js | mysql2 | connection.execute(sql, values) |
C/C++ | MySQL C API | mysql_stmt_prepare() + mysql_stmt_execute() |
Parameter | Recommended Value | Description |
useServerPrepStmts | true | Enable server-side prepared statements. By default, JDBC uses client-emulated prepared statements; setting this to true switches to server-side prepared statements, thereby improving performance for repeated execution of identical statements. |
cachePrepStmts | true | Enable client-side prepared statement caching to avoid redundant recreation of prepared statements upon each use. |
prepStmtCacheSqlLimit | 2048 | The maximum SQL length for a single prepared statement (unit: bytes). The default value is 256, which may be insufficient for complex SQL statements; it is recommended to increase this value. |
prepStmtCacheSize | 256 | The maximum number of client-side cached prepared statements. The default value is 25; it is recommended to adjust this based on the actual number of SQL statements used in the application. |
jdbc:mysql://<host>:<port>/<database>?useServerPrepStmts=true&cachePrepStmts=true&prepStmtCacheSqlLimit=2048&prepStmtCacheSize=256&rewriteBatchedStatements=true&allowMultiQueries=true
<host>, <port>, and <database> with the actual connection information of your TDSQL Boundless instance.Event type | Description |
Prepare | The audit log records the creation operation of prepared statements, including the SQL template text. |
Execute | The audit log records the execution operation of prepared statements, including the actual parameter values. |
Query | The audit log records PREPARE, EXECUTE, and DEALLOCATE PREPARE statements executed via the text protocol. |
COMMAND_CLASS, CONNECTION_ID, STATUS, and SQLTEXT, which can be used for security auditing and execution analysis.? to avoid directly concatenating user input into SQL strings, effectively preventing SQL injection attacks.DEALLOCATE PREPARE to release prepared statements after use, avoiding occupying server memory resources.useServerPrepStmts to true to use server-side prepared statements instead of client emulation, thereby achieving higher execution efficiency.cachePrepStmts and properly set prepStmtCacheSize and prepStmtCacheSqlLimit to reduce the overhead of repeatedly creating prepared statements.max_prepared_stmt_count controls the total number of prepared statements that can concurrently exist on the server. If the upper limit is reached, new PREPARE operations will return an error. The current number of created prepared statements can be viewed via SHOW GLOBAL STATUS LIKE 'Prepared_stmt_count'.Variable | Scope | Default Value | Scope | Description |
max_prepared_stmt_count | GLOBAL | 16382 | 0 ~ 4194304 | The global total number of prepared statements allowed to exist concurrently on the server (across all sessions). When the limit is reached, new PREPARE operations will return ERROR 1461 (42000): Can't create more than max_prepared_stmt_count statements |
? in a prepared statement has no fixed upper limit, but is limited by the max_allowed_packet system variable.PREPARE.; is not supported).PREPARE ... FROM @variable method is used to pass SQL text, the statement undergoes full syntax parsing during preparation. Therefore, ensure that the SQL syntax in the user variable is correct.Esta página foi útil?
Você também pode entrar em contato com a Equipe de vendas ou Enviar um tíquete em caso de ajuda.
comentários