Prepared statement
In database management systems, a prepared statement, parameterized statement, 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 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 :
- :
- Compile: The DBMS compiles the statement template, and stores the result without executing it.
- Execute: The application supplies values for the parameters of the statement template, and the DBMS executes the statement. 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".
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.
Software support
Major DBMSs, including SQLite, MySQL, Oracle, IBM Db2, Microsoft SQL Server and PostgreSQL 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.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, Perl's DBI, PHP's PDO and Python's DB-API. 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; only H2 supports this feature.
Examples
Go
// Define a BookModel type which wraps a sql.DB connection pool.
type BookModel struct
// This will insert a new book into the database.
func Insert
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
Java JDBC
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
Java
PreparedStatement provides "setters", setString, setDouble for all major built-in data types.PHP PDO
This example uses PHP and PDO:// Connect to a database named "mysql", with the password "root"
$connection = new PDO;
// Execute a request on the connection, which will create
// a table "products" with two columns, "name" and "price"
$connection->exec;
// Prepare a query to insert multiple products into the table
$statement = $connection->prepare;
$products =,
,
,
];
// Iterate through the products in the "products" array, and
// execute the prepared statement for each product
foreach
// Prepare a new statement with a named parameter
$statement = $connection->prepare;
$statement->execute;
// Use array destructuring to assign the product name and its price
// to corresponding variables
= $statement->fetch;
// Display the result to the user
echo "The price of the product is \$.";
Perl DBI
This example uses Perl and DBI:- !/usr/bin/env perl -w
use DBI;
my = ;
my $dbh = DBI->connect
or die "ERROR while connecting to database $db_name: ".
$DBI::errstr. "\n";
$dbh->do;
my $sth = $dbh->prepare;
$sth->execute foreach,, ;
$sth = $dbh->prepare;
$sth->execute;
print "$$_\n" foreach $sth->fetchrow_arrayref;
$sth->finish;
$dbh->disconnect;
C# ADO.NET
This example uses C# and ADO.NET:using )
ADO.NET
SqlCommand will accept any type for the value parameter of AddWithValue, and type conversion occurs automatically. Note the use of "named parameters" 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.
Python DB-API
This example uses Python and DB-API:import mysql.connector
with mysql.connector.connect as conn:
with conn.cursor as cursor:
cursor.execute
params =
cursor.executemany
params =
cursor.execute
Magic Direct SQL
This example uses Direct SQL from Fourth generation language like eDeveloper, uniPaaS and magic XPA from Magic Software EnterprisesVirtual username Alpha 20 init: 'sister'
Virtual password Alpha 20 init: 'yellow'
SQL Command:
Input Arguments:
1: username
2: password
PureBasic
PureBasic can manage 7 types of link with the following commandsSetDatabaseBlob, SetDatabaseDouble, SetDatabaseFloat, SetDatabaseLong, SetDatabaseNull, SetDatabaseQuad, SetDatabaseString
There are 2 different methods depending on the type of database
For SQLite, ODBC, MariaDB/Mysql use: ?
SetDatabaseString
If DatabaseQuery
;...
EndIf
For PostgreSQL use: $1, $2, $3,...
SetDatabaseString ; -> $1
SetDatabaseString ; -> $2
SetDatabaseLong ; -> $3
If DatabaseQuery
;...
EndIf