MySQL Advanced Way (iii) transaction control

Transaction
ACID transaction (acid) property
➢1. Atomicity (Atomicity)
Atomicity means that a transaction is an indivisible unit of work operations in a transaction either occur or do not occur.

. ➢2 Consistency (Consistency)
transaction from a database must - induced transformation to another state - - a consistent state.

. ➢3 isolation (Isolation)
transaction isolation means - performing a transaction can not be interfere with other transactions, i.e., operation and use of the data inside a transaction other concurrent transactions are isolated, each of the concurrently executing transactions inter can not interfere with each other.

➢4. Persistent (Durability)
Persistence refers once eleven transaction is committed, it changed data in the database is permanent, then the other operations and database failures should not have any impact on its

Creating a transaction
implicit transaction: Transaction no apparent opening and closing tags
such as insert, update, delete statement
delete from table where id = 1;
explicit transaction: The transaction has a significant opening and mark the end of
the premise: You must set up automatic submit feature is disabled
set autocommit = 0;
to see whether to open automatically submitted
SHOW VARIABLES LIKE 'autocommit';
the use of steps demonstrate affairs
# affairs open
the SET autocommit = 0;
the START TRANSACTI ON;

# Prepared a set of transaction statements
UPDATE account SET balance = 1000 WHERE username = Wuji,;
UPDATE the Account Balance = 1000 the WHERE use the SET RNAME = "Zhao";

End the transaction
ROLLBACK;
#commit;

Transaction isolation level

| |

Isolation Levels description
READ UNCOMMTTED (read uncommitted data) Allows transactions to read other things are not changing dirty reads submitted, non-repeatable read and phantom read problems will arise
READ COMMTED (read submitted data) Only allows transactions to read changes have been submitted by other transactions. Avoid dirty reads, but non-repeatable read and phantom read problems may still arise
REPEATABLE READ (repeatable read) Ensure that the transaction can be repeatedly read from a field of the same value in the duration asked this transaction, prohibiting anything else on this field to be updated. Avoid dirty reads and non-repeatable read, phantom read but problems remain.
SERIALIZABLE (serialization) Ensure that the transaction can read the same row from a table in this transaction duration asked to prohibit other transactions executed on the table insert big update, and delete operations. All concurrency issues can be avoided, but the performance is very low.

➢ Dirty read: For two transactions T1, T2, T1 T2 read the field has been updated but has not yet been submitted after the rollback if T2, T1 reads the content is temporary and ineffective.

➢ non-repeatable reads: for two transactions T1, T2, T1 read a field, and the field after the update T2, Tl again read from the same field, the value is different.

➢ phantom read: for two transactions T1, T2, T1 is read from a field in a table, and then insert a new T2 rows in the table then, if T1 is read again the same table, it will be more a few lines.

For multiple transactions running simultaneously, when the same data in these transactions to access the database, if not taken the necessary isolation mechanism, can lead to all kinds of concurrency problems:

Isolation of database transaction: database system must have the ability to isolate individual transactions run concurrently, so they do not affect each other, avoid all kinds of concurrency issues.

The extent of a transaction is isolated from other transactions is called the isolation level provides a variety of database transaction isolation levels, different isolation levels correspond to different degrees of interference, the higher the isolation level, data consistency is better, but the weaker concurrency.

Each start - a mysql program, you'll get a separate database connection for each database connection has a global variable @@ tx_isolation, indicates that the current transaction isolation level...

View the current isolation level: SELECT @@ tx_ _isolation;

Isolation Levels Dirty read Non-repeatable read Magic Reading
read uncommitted V V V
read committed x V V
repeatable read x x V
serializable x x x

Setting the current isolation level mySQL connection:
➢set Transaction Isolation Level Read committed;

Setting the global database system isolation level:
➢set Global Transaction Isolation Level Read committed;

mysq1 default high-level third compartment Read Repeatable
Oracle default second compartment committed high-level Read
savepoint
#. 3 demonstrates the use of the savepoint.
the SET autocomnit = 0;
the START TRANSACTION;
the DELETE the FROM Account the WHERE ID = 25P
SAVEPOINT A; Set # savepoint
the DELETE the WHERE the FROM Account ID = 28;
rOLLBACK the tO A; Shan rollback to the savepoint

View
Meaning: virtual table, and ordinary table as the use of
the new features mysq15.1 version appears, the data table is dynamically generated by
reusing sql statement to
simplify complex sql operation, it does not have to know the details of the query
data protection, and security of
$ Case : Zhang query name and student professional names
the SELECT S tuname, majorname
the FROM S stuinfo
the INNER the JOIN Major the ON S m 'majorid' = m.'id '.
the WHERE s.'stuname' the LIKE '%% sheets';

创建视图
CREATE VIEW v1
AS
SELECT stuname , maj orname
FROM stuinfo s
INNER JOIN major m ON s.'majorid'= m. id ;
SELECT * FROM v1 WHERE stuname LIKE '张号';

Delete view
DROP VIEW view name;

Check trying
DESC view name;

Variable
a system variable,
explained:
variables provided by the system, not the user-defined, belong to the syntax server level use:
Note:
If a global level, you need to add global, if the session level, you need to add session, if you do not write the default session

1, a system to view all variables
show global session] [Variables;
2, satisfying the condition of the system to view the variables
show globaI like [session] Variables '% char%';
. 3, see the value of a specified system variables
select @@ [session] global system variable name;
4, assigned to a system variable
mode 1;
the SET Globall [session] system variable name = value;
Second way:
the SET eGlobal [session] . The system variable name = value;
"global variables

# ① see all global variables
SHOW GLOBAL VARIABLES;

# ② view the global variable portion of the
SHOW GLOBAL VARIABLES LIKE '% char% ';

See # ③ global variable specified value of
the SELECT B @ Global the autocommit;.
The SELECT @@ TX_ISOLATION;

# ④ assignment for a specified global variable
SET @@ global autocommit = 0.;

# 1 "Global Variables
scope: will be assigned an initial value of all global variables each time you start the server for all active sessions (connections), but can not cross restart

"Session variables
scope: only the (connection) valid for the current session

# ① see all session variables
SHOW VARIABLES;
SHOW SESSION VARIABLES;
# ② view the session variable part of the
SHOW VARIABLES the LIKE '% Chark%';
SHOW SESSION VARIABLES the LIKE '% char%';
# ③ view of a specified session variable
SELECT TX_ISOLATION @@;
the SELECT @@ session.tx_isolation;
# ④ assigned a session variable
mode a:
the SET @@ TX_ISOLATION = 'Read-Uncommitted';
Second way:
the SET = the sESSION TX_ISOLATION 'Read-comnitted';
custom variables
Description : variables are user-defined, not by the system
using the steps:
declaration
assignment
use (view, compare, operations, etc.)
user variables
scope: the scope for any application in the current session (connection) is valid, in the same session variables local, that is, begin or end inside begin outside end

Assignment operator: = or: =

# ① declare and initialize
SET @ user variable name = value; or
SET @ user variable name: = value; or
SELECT @ user variable name: = value;

# ② assignment (updates the value of the user variable)
manner a ~: SET or the SELECT
SET @ user variable name = value; or
SET @ user variable name: = value; or
SELECT B user variable name: = value;
way: by INTO the SELECT
the SELECT field name ~ INTO variable FROM table;
# Example:
# declare and initialize
the SET
@ = name "john ';
the SET @ 100 = name;
the SET bCount = 1;

#赋值
SELECT COUNT (*) INTO @count
FROM employees ;

# View
SELECT @count;

# ③ using
SELECT local variable names;

Local variables
scope: it is defined only effective begin end

Applications begin end of the first sentence I

# ① statement
DECLARE variable name type;
DECLARE Variable Name Type DEFAULT value;

# ② Assignment
Method one: sET or the SELECT
SET local variable name = value; or
SET local variable names: = value; or
SELECT @ local variable names: = value;,
Second way: by the SELECT the INTO
the SELECT fields INTo local variable names FROM table;

Comparative user variables and local variables:

variable Scope Positions defined and used grammar
User Variables Current Session Anywhere session Must be added the @ symbol, do not limit the type of
Local variables BEGIN END in BEGIN END only, and the first sentence of Usually do not @ sign, necessary to define the type

Case #: Declare two variables and assign an initial value, sum, and print

# 1 User variables
the SET @ m = 1;
the SET @ = n-2;
the SET @sum @ = @ n-m +;
the SELECT SUM G;

Stored procedure
Meaning: a collection of pre-compiled SQL statements, statements understood to batch
1, to improve the reusability of code
2, to simplify the operation
3, to reduce the number of compiled and reducing the number of servers and database connections, improving efficiency
First, create a syntax
cREATE pROCEDURE stored procedure name (parameter list)
BEGIN
body of the procedure (a combination method of SQL statements)
END

Note:
1, consists of three parts parameter list
parameter mode ---- ----- Parameter Type Parameter Name
Example:
the IN stuname VARCHAR (20 is)

Parameter Mode:
the IN: This parameter can be used as an input, i.e. the value of parameter pass requires caller
OUT: This parameter can be used as output, i.e. the return value as a parameter
INOUT: This parameter can be either an input and an output, that is, the need to pass both parameter values, and return values

2, if the body of the procedure with only one - sentence, BEGIN END may be omitted

The end of the stored procedure body requires each SQL statement must be a semicolon.
The end of the stored procedure can be used DELIMITER reset
Syntax:
DELIMITER end tag
Case:
DELIMITER $
1, is created with no parameters of stored procedures
DELIMITER $
the CREATE PROCEDURE myp1 ()
BEGIN
INSERT INTO ADMIN (use RNAME, 'PAS Sword')
VALUES ( 'John1 ", 0000 ), (Lily ', 0000'), ( 'Rose', 0000"), ( "Jack", * 0000 "), ( 'Tom', '0000');
the END $

# Call
CALL myp1 () S

2, create a stored procedure with parameters in the model

Case # 1: Create stored procedures based on the name of the goddess, god queries corresponding information
the CREATE PROCEDURE myp2 (the IN beautyName VARCHAR (20))
BEGIN
* the SELECT BO.
The FROM Boys BO
RIGHT JOIN b ON bo.id Beauty b.boyfriend_ the above mentioned id =
b.name = beautyName the WHERE;
the END $

# Call
CALI myp2 ( "Liu Yan ') $

# Case 2: Create stored procedures, whether the user login is successful
the CREATE PROCEDURE myp4 (the IN username VARCHAR (20), the IN PASSWORD VARCHAR (20))
BEGIN
DECLARE the Result INT the DEFAULT 0; # declare and initialize
SELECT COUNT (*) INTO result # assigning
the FROM ADMIN
. RNAME use the WHERE ADMIN username =
. = pASSWORD the AND ADMIN password;
the SELECT IEs (Result> 0, 'success', 'failure'); # use
END $

# Call
CALL myp3 ( 'Zhang', * 8888 ') $

3, create a band out pattern stored procedure
# Case 1: According to the goddess name, returns the corresponding male name of God
the CREATE PROCEDURE myp5 (the IN beautyName VARCHAR (20), OUT boyName VARCHAR (20))
BEGIN
the SELECT BO boyName INTO boyName.
The FROM Boys BO
the INNER B the ON bo.id the JOIN Beauty ID = b.boyfriend_
. beautyName the WHERE B = name;
the END $

# Call
CALL myp5 ( "UNIT", @bName) $
the SELECT @bNameS

Case # 2: According to the goddess name, returns the corresponding male name of God and man God Charisma
the CREATE PROCEDURE myp6 (the IN beautyName VARCHAR (20), OUT boyName VARCHAR (20), OUT userCP INT)
BEGIN
the SELECT bo.boyNase, bo.usexCP INTO boyName, userCP
a PROM BO Boys
the INNER B the ON bo.id the JOIN Beauty ID = b.boyfriend_
. beautyName the WHERE B = name;
the END $

# Call
CALL myp6 (* UNIT ", @bName, Busercp) $

# 4 Create inout mode parameters with stored procedures.
# Case 1: the incoming two values a and b, a and b are double the final and returns
the CREATE PROCEDURE myp8 (a INOUT the INT, the INT INOUT b)
the BEGIN
the SET a = a 2;
the SET B = B
2;
the END $
# calling
the SET @ $ m = 10
the SET @ 20 is n-$ =
the cALL myp8 (@m, @n) S
the SELECT @m, @n $

Second, delete the stored procedure
# syntax: drop procedure stored procedure name
DROP PROCEDURE p1;
DROP PROCEDURE P2, p3; #x (error)

Third, view the stored procedure information
DESC myp2; x (error)
SHOW the CREATE PROCEDURE myp2;

Function
First, create the syntax
CREATE FUNCTION function name (parameter list) RETURNS return type
BEGIN
body of the function
END

Note:
1. The parameter list contains two parts:
Parameter name Parameter type
2 function body: there will certainly be a return statement, if there is no will complain
if there is no return statement is placed at the end of the function body is not given, but it is not recommended to
return value;
3 the function words, only the body, may be omitted end the begin
4. set mark statement using delimiter

Case presentation ---------------------------- -------------------- --------

# 1 There are no parameters returns
# case: Returns the number of company employees
the CREATE FUNCTION myf1 () RETURNS INT
BEGIN
DECLARE c INT the DEFAULT 0; defined variables
the SELECT COUNT (*)
INTO c
the FROM the Employees;
the RETURN C;
LEND $

SELECT myf1 ()$

# 2 There are parameters that return
# Case 1: the employee name, returns its wage
the CREATE FUNCTION myf2 (empName VARCHAR (20)) RETURNS DOUBLE
BEGIN
the SET @ SAL = 0; # define user variables
SELECT salary INTO @sal # Fu straight
the Employees the FROM
the WHERE Last name = empName;
the RETURN TSAL;
the END $
the SELECT myf2 ( 'k_ing') $

# Case 2: The department name, returns the average salary of the sector
the CREATE the FUNCTION myf3 (DEPTNAME VARCHAR (20 is)) the RETURNS DOUBLE
the BEGIN
the DECLARE SAL DOUBLE;
the SELECT the AVG (the salary) the INTO SAL
the FROM the Employees E
the JOIN Departments D the ON E DEPARTMENT_ID = D. .department ID
the WHERE D Department.
name = DEPTNAME;
the RETURN SAL;
the END $
the SELECT myf3 ( 'the IT') $

A create function, passing achieve two float, and between the two return
the CREATE fun1 with test_ the FUNCTION (FLOAT num1, num2 FLOAT) the RETURNS FLOAT
the BEGIN
the DECLARE the SUM FLOAT the DEFAULT 0;
the SET + num1 num2 the SUM =;
the RETURN the SUM;
the END $

SELECT test_ fun1 (1,2)$

* Third, view the function
SHOW the CREATE FUNCTION myf3;
# Fourth, the delete function
DROP FUNCTION myf3; [

Guess you like

Origin blog.51cto.com/14509987/2434178