MySQL DBA Training Session 13. User Variables and Prepared StatementsRAM N SANGWAN
WWW.RNSANGWAN.COM
YOUTUBE CHANNEL : HTTP://YOUTUBE.COM/USER/THESKILLPEDIA
TO LEARN OR TEACH JOIN WWW.THESKILLPEDIA.COM
Agenda
• Introduction
• User Variable Syntax
• Uses of Variables
• User Variable Properties
• Prepared Statements
• Using Prepared Statements
• Preparing a Statement - Example
• Prepare Statement – Considerations
• Executing a Prepared Statement
• Deallocating Prepared Statements
Introduction
• MySQL allows you to assign values to variables and refer to them later.
• This is useful when you want to save the results of calculations for use in subsequentstatements.
• User variables are written as @var_name and may be set to an integer, real, string, or NULLvalue.
User Variable Syntax
• In a SET statement, you can assign a value to a variable using either = or := as theassignment operator:
mysql> SET @var1 ='USA';
mysql> SET @var2 :=‘IND';
• In other contexts, such as in a SELECT statement, use the := assignment operator:
mysql> SELECT @var3 :='CAN';
• A SET statement can perform multiple variable assignments, separated by commas:
mysql> SET @var1 ='USA', @var2 ='GBR', @var3 ='CAN';
• If you refer to an uninitialized variable that has not been assigned a value explicitly, its value isNULL:
mysql> SELECT @var1, @var2, @var3, @var4;
Uses of Variables
• User variables can be used where expressions are allowed.
• However, they cannot be used where a literal value is required.
• For example LIMIT, which requires literal integer arguments, and the filename in LOAD DATA INFILE,which must be a literal string.
• User variables are specifically required when using EXECUTE to execute a preparedstatement.
• Each data value given as a parameter to EXECUTE must be passed as a user variable.
• User variables also are used in LOAD DATA INFILE to hold data values read from a file thatare to be transformed before being loaded into a table.
• User variables are not the same as local variables that you declare in stored routines.
User Variable Properties
• User variable names are not case sensitive. (MySQL 5 onwards.)
• User variables are specific to the client connection within which they are usedand exist only for the duration of that connection.
• A user variable used within a connection cannot be accessed by otherconnections.
• A user variable that has been assigned a non-binary string value has thesame character set and collation as the string.
Prepared Statements
• MySQL Server supports prepared statements, which are useful when youwant to run several queries that differ only in very small details.
• For example, you can prepare a statement, and then execute it multiple times,each time with different data values.
• Besides offering a convenience, prepared statements also provide enhancedperformance because the complete statement is parsed only once by theserver.
• When the parse is complete, the server and client may make use of a newprotocol that requires fewer data conversions than when sending eachstatement individually.
Using Prepared Statements
• In most circumstances, statements are prepared and executed using the programminginterface that you normally use for writing applications that use MySQL.
• However, to aid in testing and debugging, it is possible to define and use prepared statementsfrom within the mysql command-line client.
Using Prepared Statements Contd..
mysql> PREPARE my_stmtFROM ->'SELECT COUNT(*)
FROM CountryLanguage WHERE CountryCode = ?';
mysql> SET @code ='ESP';
EXECUTE my_stmt USING @code;
mysql> SET @code ='RUS';
EXECUTE my_stmt USING @code;
mysql> DEALLOCATE PREPARE my_stmt;
Preparing a Statement
• PREPARE takes two arguments:
◦ a name to assign to the statement once it has been prepared, and
◦ the text of an SQL statement.
• Prepared statement names are not case sensitive.
• The text of the statement can be given either as a literal string or as a user variable containingthe statement.
• The statement may not be complete, because data values that are unknown at preparationtime are represented by question mark ('?') characters that serve as parameter markers.
• At the time the statement is executed, you provide specific data values, one for eachparameter in the statement.
Prepare Statement –Example
• The following example prepares a statement named namepop.
mysql> PREPARE namepop
FROM 'SELECT Name, Population
FROM Country
WHERE Code = ? ';
• If the server finds a problem as it parses the statement during a PREPARE, it returns an errorand does not prepare the statement:
mysql> PREPARE error
FROM ‘SELECT NonExistingColumn
FROM Country
WHERE Code = ? ';
ERROR 1054 (42S22): Unknown column'NonExistingColumn' in'field list'
Prepare Statement – Considerations
• If you PREPARE a statement using a statement name that already exists, the server firstdiscards the prepared statement currently associated with the name, and then prepares thenew statement.
• If the new statement contains an error and cannot be prepared, the result is that no statementwith the given name will exist.
• MySQL does not allow every type of SQL statement to be prepared.
• Those that may be prepared are limited to the following:
o SELECT statements
o Statements that modify data: INSERT, REPLACE, UPDATE, and DELETE
o CREATE TABLE statements
o SET, DO, and many SHOW statements
Executing a Prepared Statement
• If the statement contains any '?' parameter markers, a data value must be supplied for each of
them by means of user variables.
• To execute a prepared statement, initialize any user variables needed to provide parameter
values, and then issue an EXECUTE USING statement:
mysql> SET @var1 ='USA';
mysql> EXECUTE namepop USING @var1;
mysql> SET @var2 ='GBR';
mysql> EXECUTE namepop USING @var2;
mysql> SELECT @var3 :='CAN';
mysql> EXECUTE namepop USING @var3;
• If you refer to a user variable that has not been initialized, its value is NULL :
mysql> EXECUTE namepop USING @var4;
Deallocating Prepared Statements
• Prepared statements are dropped automatically when they are redefined or when you closethe connection.
• However, should you wish to do so, use the DEALLOCATE PREPARE statement:
mysql> DEALLOCATE PREPARE namepop;
• MySQL also provides DROP PREPARE as an alias for DEALLOCATE PREPARE.
Thank You