Prepared statement
In database management systems (DBMS), a prepared statement, parameterized statement, (not to be confused with parameterized query) is a feature where the database pre-compiles SQL code and stores the results, separating it from data. Benefits of prepared statements are: * efficiency, because they can be used repeatedly without re-compiling * security, by reducing or eliminating SQL injection attacks A prepared statement takes the form of a pre-compiled template into which constant values are substituted during each execution, and typically use SQL DML statements such as INSERT, SELECT, or UPDATE. A common workflow for prepared statements is: # Prepare: The application creates the statement template and sends it to the DBMS. Certain values are left unspecified, called parameters, placeholders or bind variables (labelled "?" below): #: # Compile: The DBMS compiles (parses, optimizes and translates) the statement template, and stores the result without executing it. # Execute: The application supplies (or binds) values for the parameters of the statement template, and the DBMS executes the statement (possibly returning a result). The application may request the DBMS to execute the statement many times with different values.…
In database management systems (DBMS), a prepared statement, parameterized statement, (not to be confused with parameterized query) is a feature where the database pre-compiles SQL code and stores the results, separating it from data. Benefits of prepared statements are: efficiency, because they can be used repeatedly without re-compiling security, by reducing or eliminating SQL injection attacks A prepared statement takes the form of a pre-compiled template into which constant values are substituted during each execution, and typically use SQL DML statements such as INSERT, SELECT, or UPDATE. A common workflow for prepared statements is: Prepare: The application creates the statement template and sends it to the DBMS. Certain values are left unspecified, called parameters, placeholders or bind variables (labelled "?" below): Compile: The DBMS compiles (parses, optimizes and translates) the statement template, and stores the result without executing it. Execute: The application supplies (or binds) values for the parameters of the statement template, and the DBMS executes the statement (possibly returning a result). The application may request the DBMS to execute the statement many times with different values. In the above example, the application might supply the values "bike" for the first parameter and "10900" for the second parameter, and then later the values "shoes" and "7400". The alternative to a prepared statement is calling SQL directly from the application source code in a way that combines code and data. The direct equivalent to the above example is: INSERT INTO products (name, price) VALUES ('bike', '10900'); Not all optimization can be performed at the time the statement template is compiled, for two reasons: the best plan may depend on the specific values of the parameters, and the best plan may change as tables and indexes change over time. On the other hand, if a query is executed only once, server-side prepared statements can be slower because of the additional round-trip to the server. Implementation limitations may also lead to performance penalties; for example, some versions of MySQL did not cache results of prepared queries. A stored procedure, which is also precompiled and stored on the server for later execution, has similar advantages. Unlike a stored procedure, a prepared statement is not normally written in a procedural language and cannot use or modify variables or use control flow structures, relying instead on the declarative database query language. Due to their simplicity and client-side emulation, prepared statements are more portable across vendors. import import std; using mysqlx::Schema; using mysqlx::Session; using mysqlx::Table; int main() { try { Session session("localhost", 33060, "user", "password"); Schema db = session.getSchema("testdb"); Table users = db.getTable("users"); users.insert("name", "age") .values("Alice", 30) .execute(); } catch (const mysqlx::Error& e) { std::println(stderr, "MySQL error: {}", e.what()); } } namespace Wikipedia.Examples; using System; using System.Data; using Microsoft.Data.SqlClient; public class Example { static void Main(string[] args) { using (SqlCommand command = connection.CreateCommand()) { command.CommandText = "SELECT * FROM users WHERE USERNAME = @username AND ROOM = @room"; command.Parameters.AddWithValue("@username", username); command.Parameters.AddWithValue("@room", room); using (SqlDataReader dataReader = command.ExecuteReader()) { // ... } } } } ADO.NET SqlCommand will accept any type for the value parameter of AddWithValue , and type conversion occurs automatically. Note the use of "named parameters" (i.e. "@username" ) rather than "?" —this allows you to use a parameter multiple times and in any arbitrary order within the query command text. However, the AddWithValue method should not be used with variable length data types, like varchar and nvarchar. This is because .NET assumes the length of the parameter to be the length of the given value, rather than getting the actual length from the database via reflection. The consequence of this is that a different query plan is compiled and stored for each different length. In general, the maximum number of "duplicate" plans is the product of the lengths of the variable length columns as specified in the database. For this reason, it is important to use the standard Add method for variable length columns: , where ParamLength is the length as specified in the database. Since the standard Add method needs to be used for variable length data types, it is a good habit to use it for all parameter types. // Define a BookModel type which wraps a sql.DB connection pool. type BookModel struct { DB *sql.DB } // This will insert a new book into the database. func (m *BookModel) Insert(title, author string) (int, error) { stmt := "INSERT INTO book (title, author, created) VALUES(?, ?, UTC_TIMESTAMP())" // The "Exec" function will automatically prepare the statement for you, // which requires an additional round-trip to the database. // // It is possible to avoid prepared statements, if you are sure they are not needed. // See ExecerContext for details. https://pkg.go.dev/database/sql/driver#ExecerContext // // Other functions such as "Query" work the same way, // and have an equivalent interface. result, err := m.DB.Exec(stmt, title, author) if err != nil { return 0, err } id, err := result.LastInsertId() // Not supported in the Postgres driver -- use RETURNING instead. if err != nil { return 0, err } // The ID returned has the type int64, so we convert it to an int type // before returning. // // Keep in mind, on 32-bit machines, this can potentially truncate the value. // It is usually more safe to return int64 from your function directly, // which is still supported on 32-bit machines. return int(id), nil } The placeholder parameter syntax differs depending on your database. MySQL, SQL Server and SQLite use the ? notation, but PostgreSQL uses the $N notation. For example, if you were using PostgreSQL instead you would write: _, err := m.DB.Exec("INSERT INTO ... VALUES ($1, $2, $3)", ...) package org.wikipedia.examples; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import com.mysql.jdbc.jdbc2.optional.MysqlDataSource; public class Main { public static void main(String[] args) throws SQLException { MysqlDataSource ds = new MysqlDataSource(); ds.setDatabaseName("mysql"); ds.setUser("root"); try (Connection conn = ds.getConnection()) { try (Statement stmt = conn.createStatement()) { stmt.executeUpdate("CREATE TABLE IF NOT EXISTS products (name VARCHAR(40), price INT)"); } try (PreparedStatement stmt = conn.prepareStatement("INSERT INTO products VALUES (?, ?)")) { stmt.setString(1, "bike"); stmt.setInt(2, 10900); stmt.executeUpdate(); stmt.setString(1, "shoes"); stmt.setInt(2, 7400); stmt.executeUpdate(); stmt.setString(1, "phone"); stmt.setInt(2, 29500); stmt.executeUpdate(); } try (PreparedStatement stmt = conn.prepareStatement("SELECT * FROM products WHERE name = ?")) { stmt.setString(1, "shoes"); ResultSet rs = stmt.executeQuery(); rs.next(); System.out.println(rs.getInt(2)); } } } } Java PreparedStatement provides "setters" ( setInt(int), setString(String), setDouble(double), etc.) for all major built-in data types. exec('CREATE TABLE IF NOT EXISTS products (name VARCHAR(40), price INT)'); // Prepare a query to insert multiple products into the table $statement = $connection->prepare('INSERT INTO products VALUES (?, ?)'); $products = [ ['bike', 10900], ['shoes', 7400], ['phone', 29500], ]; // Iterate through the products in the "products" array, and // execute the prepared statement for each product foreach ($products as $product) { $statement->execute($product); } // Prepare a new statement with a named parameter $statement = $connection->prepare('SELECT * FROM products WHERE name = :name'); $statement->execute([ ':name' => 'shoes', ]); // Use array destructuring to assign the product name and its price // to corresponding variables [ $product, $price ] = $statement->fetch(); // Display the result to the user echo "The price of the product {$product} is \${$price}."; !/usr/bin/env perl -w use strict; use DBI; my ($db_name, $db_user, $db_password) = ('my_database', 'moi', 'Passw0rD'); my $dbh = DBI->connect("DBI:mysql:database=$db_name", $db_user, $db_password, { RaiseError => 1, AutoCommit => 1}) or die "ERROR (main:DBI->connect) while connecting to database $db_name: " . $DBI::errstr . "\n"; $dbh->do('CREATE TABLE IF NOT EXISTS products (name VARCHAR(40), price INT)'); my $sth = $dbh->prepare('INSERT INTO products VALUES (?, ?)'); $sth->execute(@$_) foreach ['bike', 10900], ['shoes', 7400], ['phone', 29500]; $sth = $dbh->prepare("SELECT * FROM products WHERE name = ?"); $sth->execute('shoes'); print "$$_[1]\n" foreach $sth->fetchrow_arrayref; $sth->finish; $dbh->disconnect; import mysql.connector with mysql.connector.connect(database="mysql", user="root") as conn: with conn.cursor(prepared=True) as cursor: cursor.execute("CREATE TABLE IF NOT EXISTS products (name VARCHAR(40), price INT)") params: list[tuple[str, int = [("bike", 10900), ("shoes", 7400), ("phone", 29500)] cursor.executemany("INSERT INTO products VALUES (%s, %s)", params) params = ("shoes",) cursor.execute("SELECT * FROM products WHERE name = %s", params) print(cursor.fetchall()[0][1]) SQL Command: SELECT * FROM users WHERE USERNAME=:1 AND PASSWORD=:2 Input Arguments: 1: username 2: password SetDatabaseString(#Database, 0, "test") If DatabaseQuery(#Database, "SELECT * FROM employee WHERE id=?") ; ... EndIf For PostgreSQL use: $1, $2, $3, ... SetDatabaseString(#Database, 0, "Smith") ; -> $1 SetDatabaseString(#Database, 1, "Yes") ; -> $2 SetDatabaseLong (#Database, 2, 50) ; -> $3 If DatabaseQuery(#Database, "SELECT * FROM employee WHERE id=$1 AND active=$2 AND years>$3") ; ... EndIf ==See also== Code injection
References
- 12.6. SQL Syntax for Prepared Statements · retrieved 2026-11-17 · rev 1367082403
Cite this reference
MLA "12.6. SQL Syntax for Prepared Statements." Oracle. 2026-11-17. http://dev.mysql.com/doc/refman/5.5/en/sql-syntax-prepared-statements.html. Accessed 24 November 2026.
Chicago "12.6. SQL Syntax for Prepared Statements." Oracle. 2026-11-17. http://dev.mysql.com/doc/refman/5.5/en/sql-syntax-prepared-statements.html.
APA Oracle. (2026). 12.6. SQL Syntax for Prepared Statements. Retrieved November 24, 2026, from http://dev.mysql.com/doc/refman/5.5/en/sql-syntax-prepared-statements.html
- Using Prepared Statements · retrieved 2026-11-17 · rev 1367082403
Cite this reference
MLA "Using Prepared Statements." 2026-11-17. http://download.oracle.com/javase/tutorial/jdbc/basics/prepared.html. Accessed 24 November 2026.
Chicago "Using Prepared Statements." 2026-11-17. http://download.oracle.com/javase/tutorial/jdbc/basics/prepared.html.
APA encyclopegia.org. (2026). Using Prepared Statements. Retrieved November 24, 2026, from http://download.oracle.com/javase/tutorial/jdbc/basics/prepared.html
- DBI-1.616 specification · retrieved 2026-11-17 · rev 1367082403
Cite this reference
MLA "DBI-1.616 specification." Bunce, Tim. 2026-11-17. https://metacpan.org/module/DBI#prepare. Accessed 24 November 2026.
Chicago "DBI-1.616 specification." Bunce, Tim. 2026-11-17. https://metacpan.org/module/DBI#prepare.
APA Bunce, Tim. (2026). DBI-1.616 specification. Retrieved November 24, 2026, from https://metacpan.org/module/DBI#prepare
- Python PEP 289: Python Database API Specification v2.0 · retrieved 2026-11-17 · rev 1367082403
Cite this reference
MLA "Python PEP 289: Python Database API Specification v2.0." "Python PEP 289: Python Database API Specification v2. 2026-11-17. https://www.python.org/dev/peps/pep-0249/. Accessed 24 November 2026.
Chicago "Python PEP 289: Python Database API Specification v2.0." "Python PEP 289: Python Database API Specification v2. 2026-11-17. https://www.python.org/dev/peps/pep-0249/.
APA "Python PEP 289: Python Database API Specification v2. (2026). Python PEP 289: Python Database API Specification v2.0. Retrieved November 24, 2026, from https://www.python.org/dev/peps/pep-0249/
- MySQL Connector/C++ Documentation · retrieved 2026-11-17 · rev 1367082403
Cite this reference
MLA "MySQL Connector/C++ Documentation." Oracle Corporation (20 January 2026). 2026-11-17. https://en.wikipedia.org/wiki/Template:Cite_web. Accessed 24 November 2026.
Chicago "MySQL Connector/C++ Documentation." Oracle Corporation (20 January 2026). 2026-11-17. https://en.wikipedia.org/wiki/Template:Cite_web.
APA Oracle Corporation (20 January 2026). (2026). MySQL Connector/C++ Documentation. Retrieved November 24, 2026, from https://en.wikipedia.org/wiki/Template:Cite_web
- X DevAPI User Guide · retrieved 2026-11-17 · rev 1367082403
Cite this reference
MLA "X DevAPI User Guide." Oracle Corporation. 2026-11-17. https://dev.mysql.com/doc/x-devapi-userguide/en/. Accessed 24 November 2026.
Chicago "X DevAPI User Guide." Oracle Corporation. 2026-11-17. https://dev.mysql.com/doc/x-devapi-userguide/en/.
APA Oracle Corporation. (2026). X DevAPI User Guide. Retrieved November 24, 2026, from https://dev.mysql.com/doc/x-devapi-userguide/en/
- PHP manual entry for PDO::prepare() · retrieved 2026-11-17 · rev 1367082403
Cite this reference
MLA "PHP manual entry for PDO::prepare()." 2026-11-17. https://www.php.net/manual/en/pdo.prepare.php. Accessed 24 November 2026.
Chicago "PHP manual entry for PDO::prepare()." 2026-11-17. https://www.php.net/manual/en/pdo.prepare.php.
APA encyclopegia.org. (2026). PHP manual entry for PDO::prepare(). Retrieved November 24, 2026, from https://www.php.net/manual/en/pdo.prepare.php
- MySQL Optimizer and Prepared Statements · retrieved 2026-11-17 · rev 1367082403
Cite this reference
MLA "MySQL Optimizer and Prepared Statements." Petrunia, Sergey (28 April 2007). 2026-11-17. https://web.archive.org/web/20180205184504/http://s.petrunia.net/blog/?p=16. Accessed 24 November 2026.
Chicago "MySQL Optimizer and Prepared Statements." Petrunia, Sergey (28 April 2007). 2026-11-17. https://web.archive.org/web/20180205184504/http://s.petrunia.net/blog/?p=16.
APA Petrunia, Sergey (28 April 2007). (2026). MySQL Optimizer and Prepared Statements. Retrieved November 24, 2026, from https://web.archive.org/web/20180205184504/http://s.petrunia.net/blog/?p=16
- MySQL Prepared Statements · retrieved 2026-11-17 · rev 1367082403
Cite this reference
MLA "MySQL Prepared Statements." Zaitsev, Peter (2 August 2006). 2026-11-17. http://www.mysqlperformanceblog.com/2006/08/02/mysql-prepared-statements/. Accessed 24 November 2026.
Chicago "MySQL Prepared Statements." Zaitsev, Peter (2 August 2006). 2026-11-17. http://www.mysqlperformanceblog.com/2006/08/02/mysql-prepared-statements/.
APA Zaitsev, Peter (2 August 2006). (2026). MySQL Prepared Statements. Retrieved November 24, 2026, from http://www.mysqlperformanceblog.com/2006/08/02/mysql-prepared-statements/
- 7.6.3.1. How the Query Cache Operates · retrieved 2026-11-17 · rev 1367082403
Cite this reference
MLA "7.6.3.1. How the Query Cache Operates." "7. 2026-11-17. http://dev.mysql.com/doc/refman/5.1/en/query-cache-operation.html. Accessed 24 November 2026.
Chicago "7.6.3.1. How the Query Cache Operates." "7. 2026-11-17. http://dev.mysql.com/doc/refman/5.1/en/query-cache-operation.html.
APA "7. (2026). 7.6.3.1. How the Query Cache Operates. Retrieved November 24, 2026, from http://dev.mysql.com/doc/refman/5.1/en/query-cache-operation.html
- Prepared Statement Objects · retrieved 2026-11-17 · rev 1367082403
Cite this reference
MLA "Prepared Statement Objects." 2026-11-17. http://www.sqlite.org/c3ref/stmt.html. Accessed 24 November 2026.
Chicago "Prepared Statement Objects." 2026-11-17. http://www.sqlite.org/c3ref/stmt.html.
APA encyclopegia.org. (2026). Prepared Statement Objects. Retrieved November 24, 2026, from http://www.sqlite.org/c3ref/stmt.html
- 20.9.4. C API Prepared Statements · retrieved 2026-11-17 · rev 1367082403
Cite this reference
MLA "20.9.4. C API Prepared Statements." Oracle. 2026-11-17. https://dev.mysql.com/doc/c-api/8.4/en/c-api-prepared-statement-interface.html. Accessed 24 November 2026.
Chicago "20.9.4. C API Prepared Statements." Oracle. 2026-11-17. https://dev.mysql.com/doc/c-api/8.4/en/c-api-prepared-statement-interface.html.
APA Oracle. (2026). 20.9.4. C API Prepared Statements. Retrieved November 24, 2026, from https://dev.mysql.com/doc/c-api/8.4/en/c-api-prepared-statement-interface.html
- 13 Oracle Dynamic SQL · retrieved 2026-11-17 · rev 1367082403
Cite this reference
MLA "13 Oracle Dynamic SQL." 2026-11-17. http://download.oracle.com/docs/cd/B10501_01/appdev.920/a97269/pc_13dyn.htm. Accessed 24 November 2026.
Chicago "13 Oracle Dynamic SQL." 2026-11-17. http://download.oracle.com/docs/cd/B10501_01/appdev.920/a97269/pc_13dyn.htm.
APA encyclopegia.org. (2026). 13 Oracle Dynamic SQL. Retrieved November 24, 2026, from http://download.oracle.com/docs/cd/B10501_01/appdev.920/a97269/pc_13dyn.htm
- SQL: Pengertian, Sejarah, Fungsi, dan Jenis Perintah SQL · retrieved 2026-11-17 · rev 1367082403
Cite this reference
MLA "SQL: Pengertian, Sejarah, Fungsi, dan Jenis Perintah SQL." 2026-11-17. https://www.bubblevy.com/2023/12/sql-pengertian-sejarah-fungsi-dan-jenis.html. Accessed 24 November 2026.
Chicago "SQL: Pengertian, Sejarah, Fungsi, dan Jenis Perintah SQL." 2026-11-17. https://www.bubblevy.com/2023/12/sql-pengertian-sejarah-fungsi-dan-jenis.html.
APA encyclopegia.org. (2026). SQL: Pengertian, Sejarah, Fungsi, dan Jenis Perintah SQL. Retrieved November 24, 2026, from https://www.bubblevy.com/2023/12/sql-pengertian-sejarah-fungsi-dan-jenis.html
- SQL Server 2008 R2: Preparing SQL Statements · retrieved 2026-11-17 · rev 1367082403
Cite this reference
MLA "SQL Server 2008 R2: Preparing SQL Statements." 2026-11-17. http://msdn.microsoft.com/en-us/library/ms175528.aspx. Accessed 24 November 2026.
Chicago "SQL Server 2008 R2: Preparing SQL Statements." 2026-11-17. http://msdn.microsoft.com/en-us/library/ms175528.aspx.
APA encyclopegia.org. (2026). SQL Server 2008 R2: Preparing SQL Statements. Retrieved November 24, 2026, from http://msdn.microsoft.com/en-us/library/ms175528.aspx
- Prepared statements and stored procedures · retrieved 2026-11-17 · rev 1367082403
Cite this reference
MLA "Prepared statements and stored procedures." a b The PHP Documentation Group. 2026-11-17. http://php.net/manual/en/pdo.prepared-statements.php. Accessed 24 November 2026.
Chicago "Prepared statements and stored procedures." a b The PHP Documentation Group. 2026-11-17. http://php.net/manual/en/pdo.prepared-statements.php.
APA a b The PHP Documentation Group. (2026). Prepared statements and stored procedures. Retrieved November 24, 2026, from http://php.net/manual/en/pdo.prepared-statements.php
- PREPARE · retrieved 2026-11-17 · rev 1367082403
Cite this reference
MLA "PREPARE." 2026-11-17. http://www.postgresql.org/docs/9.5/static/sql-prepare.html. Accessed 24 November 2026.
Chicago "PREPARE." 2026-11-17. http://www.postgresql.org/docs/9.5/static/sql-prepare.html.
APA encyclopegia.org. (2026). PREPARE. Retrieved November 24, 2026, from http://www.postgresql.org/docs/9.5/static/sql-prepare.html
Cite this article
MLA
"Prepared statement." encyclopegia.org, 2026, https://encyclopegia.org/wiki/prepared-statement. Accessed 24 November 2026.
Chicago
"Prepared statement." encyclopegia.org. Accessed November 24, 2026. https://encyclopegia.org/wiki/prepared-statement.
APA
encyclopegia.org. (2026). Prepared statement. Retrieved November 24, 2026, from https://encyclopegia.org/wiki/prepared-statement
Accessed November 24, 2026 · CC BY-SA 4.0 · citation page · JSON