mysql database - Advanced - long-term maintenance

############### ############## View

"""
1. View
View: is a virtual table, the contents of which is defined by the query. As with real tables, views, contains a series of columns and rows of data with names
View has the following characteristics;
1. Column view can come from different tables, a new relationship built on abstraction and logical sense table.
2 is a table view (virtual table) generated by the base table (the real table).
3. create and delete views do not affect the base table.
4. Update to view the content (add, delete and modify) directly affect the base table.
5. When the view from a plurality of base tables, not allowed to add and delete data.
1. Create a view
create view view name as sql query
2. Using Views
select * from view name;
3. Update view
alter view view name AS SQL statements
4. Delete view
drop view ren_view;



"""

 

############### ############## trigger

"""
2. Trigger -trigger
Trigger: monitoring a situation and trigger some kind of action.

Trigger creation syntax four elements:
1. monitoring points (table)
2. Monitor event (insert / update / delete)
3. Trigger time (after / before)
4. The triggering event (insert / update / delete)

1. Create a trigger grammar
create trigger triggerName  after/before  insert/update/delete
     on the table name for each row # This sentence is fixed
 begin
     # sql statement to be executed
 end
Note 1: after / before: only choose one, after a rear set trigger, before represents the pre-trigger
Note 2: insert / update / delete: only choose one

Scene: sold goods, the increase in orders recorded at the same time, the need to reduce the number of goods
Add three product data
insert into goods (name, num) values ​​( 'product 1', 10), ( 'product 2', 10), ( 'Product 3', 10);
If we did not use before trigger: Suppose we now sell three commodities 1, we need to do two things
1. Orders table to insert a record
insert into order_table(gid,much) values(1,3);
2. Update the product table of goods remaining number 1
update goods set num=num-3 where id=1;

trigger:
We have to do the operation: insert into order_table (gid, much) values ​​(2,3);
The corresponding actions triggered:
create trigger tg2 after insert on order_table
for each row
begin
 update goods set num = num-new.much where id = new.gid; # newly inserted row is represented by new, values ​​in a row of each column is represented by new column names.
end

Scene: When you revoke an order, we here delete an order, plus the number of items back
create trigger tg3 afert delete  on order_table
for each row
bigen
    update goods set num = num + old.much where id = old.gid; - (Note change here)
end

Scene: 2 When a user modifies a number of orders, we trigger modify how to write?
create trigger tg4 after update on order_table
for each row
begin
    update goods set num = num+old.much-new.much where id = old.gid;
end



"""

 

############### ############## Stored Procedures

"""
3. Stored Procedures
So what is a stored procedure it? How to create, view and delete stored procedures do? Stored Procedures What are the advantages?
Stored Procedures: similar functions (methods), simply in order to complete the stored procedure is a database specific features written statement collection,
The statement includes a set of SQL statements (data change search additions and deletions), conditional statements and loop statements and the like.

1. Review existing stored procedures
show procedure status;
2. Delete stored procedure
drop procedure stored procedure name;
3. To call a stored procedure
the name of the stored procedure call (the parameter / parameters of the type of data type name);

#############################
4. Create Stored Procedures
1. Experience Package #
create procedure p1 ()
begin
    select * from account;
end

# 2, SQL experience parameters
create procedure p2(in i int,out n varchar(50))
begin
 select name into n from account where id = i;
end

-- transfer
set @name =null;
CALL p2(1,@name);
select @name;
Note 1: mysql There are three types of access parameters: respectively:. 1 in the type of parameter types 2.out 3. inout and out parameters a parameter type
Note 2: into keyword query results to perform in front of the field into the back of the variables.

# 3.SQL experience control
 create procedure p3(in x int,in c char(1))
 begin
    if c ='d' then
         select * from account where money >x;
   else
         select * from account where money <x;
  end if;
end

Experience cycle # 4: 1-100 calculated and accumulated, and returns the results.
create procedure p4(inout n int)
begin
      DECLARE sum int default 0; - provided the sum of variables, and specifies the initial value 0
      declare i int; - declare variables
      set i = 0; - is set by setting the value of variable
    while i <= n DO - start the cycle
            set sum = sum +i;
            set i = i+1;
      end while; - end of the cycle

    select sum; - provide results

     set n = sum; - the calculation result to the n-output variable;
end;

 -- transfer:
 set @n = 100;
 call p4(@n);
 select @n;


"""

 

############### ############## function

 

"""
4. Functions
There are a lot of function, subsequent use to say:

For example:
Function control flow
CASE WHEN[test1] 
THEN [result1]...
ELSE [default] END # If testN is true, then return resultN, otherwise default

CASE [test] WHEN[val1] 
THEN [result]...
ELSE [default] END # valN equal and if the test is returned resultN, otherwise default

IF (test, t, f) # If the test is true, return t; otherwise f

IFNULL (arg1, arg2) # If arg1 is not empty, return arg1, arg2 otherwise
E.g:
SELECT IFNULL ( 'bbb', 'abc'); results: bbb
SELECT IFNULL (null, 'abc'); result: abc

NULLIF (arg1, arg2) # If arg1 = arg2 return NULL; otherwise arg1
E.g:
SELECT NULLIF ( 'bbb', 'bbb'); result: null
SELECT NULLIF ( 'aaa', 'bbb'); the result is: aaa



"""

 

############### ############## Affairs

"""

5. Transaction Processing
First, what is a transaction
A set of sql statement batch execution, execution or all succeed or all fail to perform

Second, why this technology
A to B to draw money, -1000 yuan account A, B accounts would +1000 yuan, the two update statements must be executed as a whole,
Otherwise, deducting money the A, B did not add money to this situation difficult to handle.

Also important to note:
Only in MySQL database engine used Innodb database or table only support transactions.
Transactions can be used to maintain the integrity of the database to ensure that the bulk of the SQL statements either all executed or not executed all.
Transaction management for insert, update, delete statement

Third, transaction control statements:
BEGIN or START TRANSACTION; explicitly open a transaction;
COMMIT; may also be used COMMIT WORK, but the two are equivalent. COMMIT commits the transaction, and the database has called all modifications permanent;
ROLLBACK; there may be used ROLLBACK WORK, but the two are equivalent. Rollback end user transaction and to withdraw all uncommitted changes under way;
SAVEPOINT: savepoint, you can put a thing is divided into several parts when performing rollback ROLLBACK can be specified at what position.
Note: SET AUTOCOMMIT = 0; disable automatic submission and SET AUTOCOMMIT = 1 enable auto-commit.

Example: Transfer to Luban Yi

1. Create a table
create table account(
    id int(50) not null auto_increment primary key,
    name VARCHAR(50) not null,
    money DOUBLE(10,2) not NULL
);
2. Insert Data
insert into account (id, name, money) values ​​(1, 'Luban', 250), (2, 'Yi', 5000);
3. Perform transfers
start transaction; - open things
 - execute sql statement operation
 update account set money = money - 500 where id =1;
 update account set money = money+500 where id = 2;

commit; - submit things manually
rollback; - the rollback of things

-- View Results
select * from account;

4. Save Point use
START TRANSACTION ;
insert into account (name,money) values('李元芳',1000);
SAVEPOINT s1; - set a savepoint
insert into account (name,money) values('张桂枝',1500);
ROLLBACK to s1; - things to roll back to the save point <br> COMMIT; - submit things


"""

 

############### ############## data lock

"""
6. Data Lock
Demand: There is an account of two people to operate this account at the same time, A To account recharge 100, B 100 removed from the account must look at the balance of the account and then the operation before the operation.

Basic concepts locks
When concurrent transactions simultaneously access a resource, it may result in inconsistent data and therefore need a mechanism to access the data of the order, in order to ensure the consistency of data in the database.

2. The basic types of locks
Multiple transactions simultaneously read an object when it is not in conflict. At the same time read and write, or write at the same time will produce conflict. Therefore, in order to improve the performance of concurrent database,
Usually we define two types of locks: shared locks and exclusive locks.
2.1 shared lock (Shared Lock, also known as S-lock)
Shared lock (S) denotes the data read operation. Therefore, multiple transactions can be simultaneously shared locks on to a target. (If not the dressing room door was locked, customers are able to simultaneously go visit)
2.2 exclusive lock (Exclusive Lock, also known as X lock)
Exclusive lock (X) represents the data write operation. If a transaction object plus exclusive lock, other transactions can not give it add any lock.
(A customer to the dressing room locked from the inside, and other customers want to use this dressing room, only to wait for the lock from the inside to open).

3. The actual development of the common two locks:
3.1 pessimistic locking the name suggests, is very pessimistic, pick up data every time the thought that others will modify, so every time locked in time to get the data,
So that others will want to take this data block (blocking) until it got locked. Traditional relational database inside to use a lot of that lock mechanism.

Note: To use pessimistic locking, we have to turn off the automatic submission mysql MySQL database attributes as default autocommit mode.
In other words, when you perform an update, MySQL will immediately submit the results. Close to automatically submit commands: set autocommit = 0;
After setting the autocommit, we can perform our normal business up. details as follows:
- 0. begin transaction
start transaction;
- 1. The account balance inquiries
set @m = 0; - Account Balance
select money into @m from account where id = 1 for update;
select @m;
- 2. Modify the account balance
update account set money = @m -100 where id = 1;
select * FROM account where id = 1;
- 3. commits the transaction
commit;
In another execution of the query page:
- 0. begin transaction
start transaction;
- 1. The account balance inquiries
set @m = 0; - Account Balance
select money into @m from account where id = 1 for update;
select @m;
- 2. Modify the account balance
update account set money = @m +100 where id = 1;
select * FROM account where id = 1;
- 3. commits the transaction
commit;
Will find the current query will enter the wait state, does not show data, when submitted to the above sql finished things, the current sql show results.
Note 1: When using pessimistic locking, if the primary key is not specified in the table, the table will be locked operation.
Note 2: pessimistic locking ensures data security, locking data when the data is operated not be accessed, but it will bring a lot of performance problems.
Therefore, use pessimistic locking in the actual development is relatively small.  

3.2 optimistic locking, by definition, is very optimistic, pick up data every time that others are not modified, so it will not be locked,
But when the update will determine what others during this time did not go to update the data, you can use the mechanisms of the version number. 

Use optimistic locking in two ways:
1. Use the data version (Version) recording mechanism to achieve, which is the most common kind of optimistic locking implementation.
What version of the data? That is, a version identifier of data increases, is generally achieved by adding a digital type of database table "version" field.
When reading data, the version value of the field is read out with the data updated every time, this version by one.
When we submit updated information to determine the current version of the database table with the first taken out of the version corresponding to the value recorded for comparison,
If the current version of the database table is equal to the value of the first version is taken out, it is to be updated, otherwise considered stale data.
 Code Example:
- 1. The account balance inquiries
set @m = 0; - Account Balance
select money into @m from account where id = 1 ;
select @m;
- 2. Query version
set @version = 0; - version number
select version into @version from account where id = 1 ;
select @version;
- 3. Modify the account balance
update account set money = @m -100,version=version+1 where id = 1 and version = @version;
select * FROM account where id = 1;

2. optimistic locking of the first and second implementation almost equally in need optimistic lock control table to add a field, the name does not matter,
Field type using a time stamp (datatime), and similar to the above version,
Also check the current time stamp data in the database and update themselves before taking to the timestamp update submitted in time comparison, if the same is OK, otherwise version conflicts.

Optimistic and pessimistic locking lock advantages and disadvantages:
Other kinds of locks have their own little drawback, which is better not simply speaking.
Optimistic locking applies to the write relatively few cases, namely when the conflict is really rare, so the lock can save the cost, increase the overall throughput of the system.
But if often conflict, the upper application will continue to retry the operation, but rather so that the reduced performance, it is more appropriate with pessimistic locking in this case.


"""

 

############### database backup ##############

"""
7. Database Backup
mysqldump command data in the database backup into a text file. And data tables stored in the table structure generated text file.
Mysqldump command works is very simple. It first find the table structure to be backed up, and then generate a CREATE statement in a text file.
Then, all the records in the table converted into an INSERT statement. Then these statements, it is possible to create tables and insert data

1. Using mysqldump to achieve logical backup \
#grammar:
# Mysqldump -h -u user name -p password server database name> .sql backup file
# Example:
# Single database backup
mysqldump -uroot -p123456 db1 > c:/db1.sql
mysqldump -uroot -p123456 db1 table1 table2 > c:/db1-table1-table2.sql
 # Multi-database backup
mysqldump -uroot -p123456 --databases db1 db2 mysql db3 > c:/db1_db2_mysql_db3.sql
 # Back up all libraries
mysqldump -uroot -p123456 --all-databases > c:/all.sql

2. Restore the logical backup 
# In the mysql command, import a backup file with the source command:
mysql> USE database name;
mysql> source backup file .sql;
Note: You can only execute in cmd command interface source, can not be executed inside source command in mysql tools, it will complain, because mysql.exe cmd is a direct call to execute the command.  

"""

 

############### ############## end of line

 

Guess you like

Origin www.cnblogs.com/andy0816/p/12275357.html