Prepared Statement
   HOME

TheInfoList



OR:

In
database management system In computing, a database is an organized collection of data or a type of data store based on the use of a database management system (DBMS), the software that interacts with end users, applications, and the database itself to capture and an ...
s (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 In computing, SQL injection is a code injection technique used to attack data-driven applications, in which malicious SQL statements are inserted into an entry field for execution (e.g. to dump the database contents to the attacker). SQL injec ...
attacks A prepared statement takes the form of a pre-compiled
template Template may refer to: Tools * Die (manufacturing), used to cut or shape material * Mold, in a molding process * Stencil, a pattern or overlay used in graphic arts (drawing, painting, etc.) and sewing to replicate letters, shapes or designs C ...
into which constant values are substituted during each execution, and typically use SQL DML statements such as
INSERT An SQL INSERT statement adds one or more records to any single table in a relational database. Basic form Insert statements have the following form: The number of columns and values must be the same. If a column is not specified, the default va ...
, 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 A stored procedure (also termed prc, proc, storp, sproc, StoPro, StoredProc, StoreProc, sp, or SP) is a subroutine available to applications that access a relational database management system (RDBMS). Such procedures are stored in the database d ...
, 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
DBMS In computing, a database is an organized collection of data or a type of data store based on the use of a database management system (DBMS), the software that interacts with end users, applications, and the database itself to capture and ana ...
s, including
SQLite SQLite ( "S-Q-L-ite", "sequel-ite") is a free and open-source relational database engine written in the C programming language. It is not a standalone app; rather, it is a library that software developers embed in their apps. As such, it ...
,
MySQL MySQL () is an Open-source software, open-source relational database management system (RDBMS). Its name is a combination of "My", the name of co-founder Michael Widenius's daughter My, and "SQL", the acronym for Structured Query Language. A rel ...
,
Oracle An oracle is a person or thing considered to provide insight, wise counsel or prophetic predictions, most notably including precognition of the future, inspired by deities. If done through occultic means, it is a form of divination. Descript ...
, IBM Db2,
Microsoft SQL Server Microsoft SQL Server is a proprietary relational database management system developed by Microsoft using Structured Query Language (SQL, often pronounced "sequel"). As a database server, it is a software product with the primary function of ...
and
PostgreSQL PostgreSQL ( ) also known as Postgres, is a free and open-source software, free and open-source relational database management system (RDBMS) emphasizing extensibility and SQL compliance. PostgreSQL features transaction processing, transactions ...
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 Java is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea (a part of Pacific Ocean) to the north. With a population of 156.9 million people (including Madura) in mid 2024, proje ...
's
JDBC Java Database Connectivity (JDBC) is an application programming interface (API) for the Java (programming language), Java programming language which defines how a client may access a database. It is a Java-based data access technology used for Java ...
,
Perl Perl is a high-level, general-purpose, interpreted, dynamic programming language. Though Perl is not officially an acronym, there are various backronyms in use, including "Practical Extraction and Reporting Language". Perl was developed ...
's DBI,
PHP PHP is a general-purpose scripting language geared towards web development. It was originally created by Danish-Canadian programmer Rasmus Lerdorf in 1993 and released in 1995. The PHP reference implementation is now produced by the PHP Group. ...
's PDO and
Python Python may refer to: Snakes * Pythonidae, a family of nonvenomous snakes found in Africa, Asia, and Australia ** ''Python'' (genus), a genus of Pythonidae found in Africa and Asia * Python (mythology), a mythical serpent Computing * Python (prog ...
'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 (m *BookModel) Insert(title, author string) (int, error) 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)", ...)


Java JDBC

This example uses
Java Java is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea (a part of Pacific Ocean) to the north. With a population of 156.9 million people (including Madura) in mid 2024, proje ...
and
JDBC Java Database Connectivity (JDBC) is an application programming interface (API) for the Java (programming language), Java programming language which defines how a client may access a database. It is a Java-based data access technology used for Java ...
: 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" (setInt(int), setString(String), setDouble(double), etc.) for all major built-in data types.


PHP PDO

This example uses
PHP PHP is a general-purpose scripting language geared towards web development. It was originally created by Danish-Canadian programmer Rasmus Lerdorf in 1993 and released in 1995. The PHP reference implementation is now produced by the PHP Group. ...
and PDO: 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">bike',_10900.html" ;"title=" ['bike', 10900"> ['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) // 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 is \$.";


Perl DBI

This example uses
Perl Perl is a high-level, general-purpose, interpreted, dynamic programming language. Though Perl is not officially an acronym, there are various backronyms in use, including "Practical Extraction and Reporting Language". Perl was developed ...
and DBI: #!/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, ) 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 "$$_ n" foreach $sth->fetchrow_arrayref; $sth->finish; $dbh->disconnect;


C# ADO.NET

This example uses C# and
ADO.NET ADO.NET is a data access technology from the Microsoft .NET Framework that provides communication between relational and non-relational systems through a common set of components. ADO.NET is a set of computer software components that programmers ...
: using (SqlCommand command = connection.CreateCommand()) 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: {{code, lang=csharp, 1=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.


Python DB-API

This example uses
Python Python may refer to: Snakes * Pythonidae, a family of nonvenomous snakes found in Africa, Asia, and Australia ** ''Python'' (genus), a genus of Pythonidae found in Africa and Asia * Python (mythology), a mythical serpent Computing * Python (prog ...
and DB-API: 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 = "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() 1])


Magic Direct SQL

This example uses Direct SQL from 4GL, 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

PureBasic PureBasic is a commercial software, commercially distributed procedural programming, procedural computer programming language and integrated development environment based on BASIC and developed by Fantaisie Software for Microsoft Windows, Windo ...
(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


See also

*
Code injection Code injection is a computer security exploit where a program fails to correctly process external data, such as user input, causing it to interpret the data as executable commands. An attacker using this method "injects" code into the program whi ...


References

Databases SQL Articles with example C Sharp code Articles with example Perl code Articles with example PHP code Articles with example Python (programming language) code Articles with example Java code