An introduction to prepared statements
MySQL supports server-side prepared statements, which utilize an efficient client/server binary protocol. Prepared statements that replace parameter values with placeholders have the following two benefits:
- There is less overhead in parsing the statement each time the statement is executed. Typically, database applications process a large number of similar statements that only change literals or variable values in clauses, such as the WHERE clause for queries and deletes, the UPDATE clause for updates, and the VALUES clause for inserts.
- Prevent SQL injection attacks. Parameter values can contain unescaped SQL quotes as well as delimiters.
You can use server-side prepared statements through client-side programming interfaces, such as the MySQL C API client library or MySQL Connector/C for C programming.
2. Execution order of prepared statements in C API
To prepare and execute a statement, an application follows these steps:
1. Create a prepared statement handle with the mysql_stmt_init() function. To prepare a statement on the server, call mysql_stmt_prepare() and pass it a string containing the SQL statement.
2. If the statement produces a result set, call mysql_stmt_result_metadata() to get the metadata of the result set. The metadata result set indicates how many columns are in the result and contains information about each column.
3. Use mysql_stmt_bind_param() to set the value of each parameter. All parameters must be assigned values, otherwise statement execution will return an error or produce unexpected results.
4. Call mysql_stmt_execute() to execute a statement.
5. If the statement produces a result set, call mysql_stmt_bind_result() to bind the data cache to receive the value for each row.
6. Repeatedly call mysql_stmt_fetch() to get the data of each row and store it in the bound cache.
7. Repeat steps 3 to 6 if necessary, by changing the parameter values and re-executing the statement.