In database management systems (DBMS), a prepared statement or parameterized statement is a feature used to execute the same or similar database statements repeatedly with high efficiency. Typically used with SQL statements such as queries or updates, the prepared statement takes the form of a template into which certain constant values are substituted during each execution.
The typical workflow of using a prepared statement is as follows:
INSERT INTO products (name, price) VALUES (?, ?);As compared to executing statements directly, prepared statements offer two main advantages:[1]
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.[3] Implementation limitations may also lead to performance penalties; for example, some versions of MySQL did not cache results of prepared queries.[4] 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.
Major DBMSs, including MySQL,[5] Oracle,[6] DB2,[7] Microsoft SQL Server[8] and PostgreSQL[9] widely support prepared statements. Prepared statements are normally executed through a non-SQL binary protocol for efficiency and protection from SQL injection, but with some DBMSs such as MySQL prepared statements are also available using a SQL syntax for debugging purposes.[10]
A number of programming languages support prepared statements in their standard libraries and will emulate them on the client side even if the underlying DBMS does not support them, including Java's JDBC,[11] Perl's DBI,[12] PHP's PDO [1] and Python's DB-API.[13] Client-side emulation can be faster for queries which are executed only once, by reducing the number of round trips to the server, but is usually slower for queries executed many times. It resists SQL injection attacks equally effectively.
Many types of SQL injection attacks can be eliminated by disabling literals, effectively requiring the use of prepared statements; as of 2007 only H2 supports this feature.[14]
This example uses Java and JDBC:
import com.mysql.jdbc.jdbc2.optional.MysqlDataSource; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; 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.
This example uses PHP and PDO:
<?php $stmt = null; try { $conn = new PDO("mysql:dbname=mysql", "root"); $conn->exec("CREATE TABLE IF NOT EXISTS products (name VARCHAR(40), price INT)"); $stmt = $conn->prepare("INSERT INTO products VALUES (?, ?)"); $params = array(array("bike", 10900), array("shoes", 7400), array("phone", 29500)); foreach ($params as $param) { $stmt->execute($param); } $stmt = $conn->prepare("SELECT * FROM products WHERE name = ?"); $params = array("shoes"); $stmt->execute($params); echo $stmt->fetch()[1]; } finally { if ($stmt !== null) { $stmt->closeCursor(); } } ?>
This example uses Perl and DBI:
#!/usr/bin/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;
This example uses C# and ADO.NET:
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:
command.Parameters.Add(ParamName, VarChar, ParamLength).Value = ParamValue, 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.
This example uses Python and DB-API:
import mysql.connector conn = None cursor = None try: conn = mysql.connector.connect(database="mysql", user="root") cursor = conn.cursor(prepared=True) cursor.execute("CREATE TABLE IF NOT EXISTS products (name VARCHAR(40), price INT)") params = [("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]) finally: if cursor is not None: cursor.close() if conn is not None: conn.close()
This example uses Direct SQL from Fourth generation language like eDeveloper, uniPaaS and magic XPA from Magic Software Enterprises
Virtual username Alpha 20 init: 'sister'
Virtual password Alpha 20 init: 'yellow'
SQL Command: SELECT * FROM users WHERE USERNAME=:1 AND PASSWORD=:2
Input Arguments:
1: username
2: password
PureBasic (since v5.40 LTS) can manage 7 types of link with the following commands
SetDatabaseBlob, SetDatabaseDouble, SetDatabaseFloat, SetDatabaseLong, SetDatabaseNull, SetDatabaseQuad, SetDatabaseString
There are 2 different methods depending on the type of database
For SQLite, ODBC, MariaDB/Mysql use: ?
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