当前位置:网站首页>Database day-2

Database day-2

2022-06-09 13:04:00 Right ear needs oil

Catalog

Daily test

Last week's content review

Evolution of stored data

The concept of databases

 mysql brief introduction

 sql sentence

  Important concepts

 mysql install

mysql Introduction to main documents

  initial sql sentence

  Environment variables and system service configuration

Change Password

  Forget the password

  The configuration file

basic SQL sentence

Summary of today's content

Today's content is detailed

Storage engine

  Complete syntax for creating tables

Basic data type

integer

Strict mode

floating-point

Character type

Time type

classification

  Enumeration and collection type

summary


Daily test

  • Briefly describe the nature and classification of database

  • MySQL For libraries 、 surface 、 Data addition, deletion, modification and query statements

    1· Database is an application based on network communication 
    2· library ( Folder )
    # Create database 
    create database db1;
    create database db2 charset="gbk";
    # Query a database 
    show create database db1;
    show databases;
    # Delete database 
    drop database db1;
    # modify the database 
    alter database db1 charset="utf8";
     surface ( file )
    # When operating tables, you need to specify the library 
    # View the name of the current library 
    select databases();
    # Switch Library 
    use db1;
    # Create a table 
    create table t1(id int,name char(4));
    # Query all tables 
    show tables;
    show create table t1;
    describe t1;
    # Delete a table 
    drop tables t1;
    # Modify the form 
    alter table t1 modify name char(16);
    """
    create table db2.t1(id int);# Create tables under different libraries 
    """
     data ( The contents of the document )
    """
     There must be a database and a table to perform data operations 
    """
    # increase 
    insert into t1 values(1,"jason");
    insert into t1 values(1,"jason"),(2,"alex"),(3,"egon");
    # Change 
    update t1 set name="zhangmei" where id > 1;
    # check 
    select * from t1;# Inquire about t1 All contents of the form 
    select name from t1;# Accurate query content 
    # Delete 
    delect from t1 where id > 1;
    delect from t1 where name="jason";
    delete from t1;# Clear the data in the table 
    

    Last week's content review

  • Evolution of stored data

"""
1  Create documents at will 、 Data formats are also very different 
    jason|123
    egon~123
    tank+123
2  Software development catalog specification 
     The general location of data storage is defined 
3  From stand-alone to networking   How to operate 
     The data is stored uniformly and in a fixed format 
     Store all the data originally stored locally to a place based on network communication 
     Then all clients go to this place to operate data uniformly 
"""

The concept of databases

"""
In fact, it is an application based on network communication

That means you can also develop your own database software
It also means that there are many database software on the market
"""
Relational type
    MySQL、oracle、access、SQL server、sqlite
Non relational
    redis、mongodb( Most like a relational database, a non relational database )、memcache

Relational type
     Data is constrained or related to each other
    Stored data is usually in tabular form
Non relational
     Usually, the K、V Store data in the form of key value pairs

 mysql brief introduction

"""
In fact, it is an application based on network communication
MySQL Free open source
The utilization rate of enterprises is wide  
Easy to use studious
"""

 sql sentence

"""
Server side
client
MySQL Support multiple types of clients
    1. Write your own client
    2. Other programming languages (python、java、php...)

How to be compatible
    1. I am awesome Automatically distinguish corresponding languages
    2. Uniform standard (******)
"""

  Important concepts

"""
library          Folder
surface          file
Record          Lines of data in the file

Header          The fields in the first row of the table
Field          Field name + Field type
"""

 mysql install

"""
1  Version of the problem 
    IT Generally, the industry will not directly use the latest version of the software 
    ( If you make an unknown error while using a certain module or software   It really can't be solved , At this time, we should consider whether it is a module or software compatibility problem )
     We use 5.6 Version as an example ( The most popular version on the market )
    python The interpreter recommends that you use 3.6 edition   Other versions have compatibility problems with some modules 
2  Just install it on the official website ( Everyone should install it independently )
"""

mysql Introduction to main documents

"""
bin Two startup programs under the file
mysqld   Server side
mysql   client
"""
mysqld Start the server first
Then the client connects
    mysql -h ... -P ... -uroot -p
        Abbreviation
        mysql -uroot -p
            No password is required for the first connection Just go back
        
        When you belong to mysql Discovery can also be connected to the server
             But this time it's tourist mode

  initial sql sentence

"""
sql A statement is a sign that ends with a semicolon ;

Cancel the execution of written content
    \c

View all library names
show databases;

Quit the server
    quit
    exit
"""

  Environment variables and system service configuration

"""
environment variable
     take bin Add the directory path to the system environment variable
    
When making system services cmd Be sure to run as an administrator
    mysqld --install
    
    mysqld --remove
"""

Change Password

mysqladmin -uroot -p Original password password New password ;

# Directly in cmd Input without entering the terminal

  Forget the password

"""
1 Start the server by skipping the authorization table
    mysqld --skip-grant-tables
2 Directly log in to the administrator account without password
    mysql -uroot -p
3 Reset the password of the current user
    update mysql.user set password=password(123) where user='root' and host='localhost';
    
    flush privileges;
4 Then start the server in the normal way
"""

  The configuration file

"""
MySQL Configuration file for   The corresponding configuration will be automatically loaded at startup 
\s   Coding inconsistency found 
"""
[mysql]  
...
[mysqld]
...
[client]
...
 Coding configuration is not required   Copy directly to use 

basic SQL sentence

In fact, the essence of our programmers' writing is the addition, deletion, modification and query of data , Nothing big

""" Add, delete, modify and query the database """
create database db1;​
show databases;
show create database db1;
​alter database db1 charset='gbk';
​drop database db1;​
""" For the addition, deletion, modification and query of the table """
#  How to view the current library 
select database();
#  Switch the current library 
use db1;​
create table t1(id int,name char);
​show tables;show create table t1;
desc t1;  >>>:  Full name  describe t1;    
alter table t1 modify name char(16);​
drop table t1;​
""" Add, delete, modify and query records """
#  Make it clear   Have libraries and tables   To operate the record 
insert into t1 values(1,'jason'),(2,'egon');
​select * from t1;
select name from t1;​
update t1 set name='DSB' where name='egon';​
delete from t1;delete from t1 where id > 1;

Summary of today's content

  • Storage engine

  • data type

    integer

    floating-point

    Character type

    The date type

    Enumeration and collection type

  • constraint condition

Today's content is detailed

Storage engine

There are many file formats in daily life , And there will be different storage methods and processing mechanisms for different file formats (txt,pdf,word,mp4...)

For different data, there should be corresponding different processing mechanisms to store

The storage engine is a different processing mechanism

MySQL The main storage engine

  • Innodb

    yes MySQL5.5 Version and later default storage engine

    Storing data is more secure

  • myisam

    yes MySQL5.5 The default storage engine before version

    Faster than Innodb faster But we pay more attention to data security

  • memory

    Memory engine ( All the data is stored in memory ) Loss of power-off data

  • blackhole

    Whatever you save , They all disappeared immediately ( Black holes )

  • """
    #  See all the storage engines 
    show engines;
    
    #  Different storage engines store tables   Similarities and differences 
    create table t1(id int) engine=innodb;
    create table t2(id int) engine=myisam;
    create table t3(id int) engine=blackhole;
    create table t4(id int) engine=memory;
    
    #  Save the data 
    insert into t1 values(1);
    insert into t2 values(1);
    insert into t3 values(1);
    insert into t4 values(1);
    """

  Complete syntax for creating tables

#  grammar 
create table  Table name (
     Field name 1  type ( Width )  constraint condition ,
     Field name 2  type ( Width )  constraint condition ,
     Field name 3  type ( Width )  constraint condition 
)
#  Be careful 
1  Field names cannot be repeated in the same table 
2  Width and constraints are optional ( Write but not write )  The field name and field type are required 
     Constraints are written   It also supports writing multiple 
     Field name 1  type ( Width )  constraint condition 1  constraint condition 2...,
    create table t5(id);   Report errors 
3  The last line cannot have a comma 
    create table t6(
        id int,
        name char,
    );    Report errors 
""" Add """
#  Width 
     Generally speaking, it refers to the limitation of data storage 
    create table t7(name char);   The default width is 1
    insert into t7 values('jason');
    insert into t7 values(null);   keyword NULL
         Different effects will appear for different versions 
            5.6 Strict mode is not enabled by default   It's a rule that only one character can be saved. You've given more than one character , Then I'll automatically intercept it for you 
            5.7 Version and above or with strict mode enabled   So the rule is only a few   You can't go beyond that , Once out of range, report an error immediately  Data too long for ....
""" Does the strict mode work ?"""
MySQL5.7 In later versions, strict mode is enabled by default 
 Guidelines for using databases :
     Let the database work as little as possible   Don't put extra pressure on the database 
#  constraint condition  null  not null Can't insert null
create table t8(id int,name char not null);
"""
 What is the relationship between width and constraints 
     Width is used to limit the storage of data 
     Constraints are additional constraints added to the width 
"""

Basic data type

integer

  • classification

    TINYINT SMALLINT MEDUIMINT INT BIGINT

  • effect

    Storage Age 、 Grade 、id、 number wait

  • """
     With TINYINT 
    	 Is there a sign 
    		 By default, it is signed (-128,127)
    	 What will be beyond 
    		 If the limit is exceeded, only the maximum acceptable value will be saved 
    """
    create table t9(id tinyint);
    insert into t9 values(-129),(256);
    
    #  One of the constraints is unsigned  Unsigned (0,255)
    create table t10(id tinyint unsigned);
    
    
    create table t11(id int);
    # int The default is also signed   
    #  Integer types are signed by default 
    
    #  For integers   What is the width in parentheses 
    create table t12(id int(8));
    insert into t12 values(123456789);
    
    """
     special case : Only the numbers in integer brackets do not represent the limit digits 
    id int(8)
    	 If the number doesn't exceed 8 position   By default, fill in the space to 8 position 
    	 If the number goes beyond 8 position   Then save a few of them ( However, the maximum scope should be observed )
    """
    create table t13(id int(8) unsigned zerofill);
    #  use 0 Fill to 8 position 
    
    #  summary :
     For integer fields   There is no need to specify the width in brackets   Because its default width and enough to display all the data 

    Strict mode

#  How to view strict mode 
show variables like "%mode";

 Fuzzy matching / Inquire about 
	 keyword  like
		%: Match any number of characters 
        _: Match any single character 

#  Change the strict pattern 
	set session   Valid only in the current window 
    set global    Global availability 
    
    set global sql_mode = 'STRICT_TRANS_TABLES';
    
     After the modification   Re enter the server 

floating-point

  • classification

    FLOAT、DOUBLE、DECIMAL

  • effect

    height 、 weight 、 Salary

#  Storage limits 
float(255,30)  #  in total 255 position   The fraction takes up 30 position 
double(255,30)  #  in total 255 position   The fraction takes up 30 position 
decimal(65,30)  #  in total 65 position   The fraction takes up 30 position 

#  Accuracy verification 
create table t15(id float(255,30));
create table t16(id double(255,30));
create table t17(id decimal(65,30));
""" Don't use the reverse key for me in the early stage   All the orders were given by hand !!! Increase proficiency """

insert into t15 values(1.111111111111111111111111111111);
insert into t16 values(1.111111111111111111111111111111);
insert into t17 values(1.111111111111111111111111111111);

float < double < decimal
#  It should be combined with actual application scenarios   All three can be used 

Character type

  • classification
char
	 Fixed length 
	char(4)	  If the data exceeds four characters, an error will be reported directly   Not enough four characters to complete the space 
varchar
	 Lengthening 
	varchar(4)   If the data exceeds four characters, an error will be reported directly   Not enough to save a few 
"""
create table t18(name char(4));
create table t19(name varchar(4));

insert into t18 values('a');
insert into t19 values('a');

#  Introduce a small method  char_length Statistics field length 
select char_length(name) from t18;
select char_length(name) from t19;
"""
 The first thing is for sure  char What is stored on the hard disk is absolutely real data   With a space 
 But on display MySQL Will automatically remove the extra space 
"""

#  Revise again sql_mode  Give Way MySQL Don't do automatic culling 
set global sql_mode = 'STRICT_TRANS_TABLES,PAD_CHAR_TO_FULL_LENGTH';
  • char And varchar contrast
  • """
    char
    	 shortcoming : Waste space 
    	 advantage : Access is simple 
    		 Access data directly according to fixed characters 
    		jason egon alex wusir tank 
    		 Save according to five characters   Take also directly according to the five characters 
    		
    varchar
    	 advantage : Save a space 
    	 shortcoming : Access is cumbersome 
    		1bytes+jason 1bytes+egon 1bytes+alex 1bytes+tank 
    		
    		 When saving, you need to make a header 
    		 When fetching, you need to read the header first   Then the real data can be read 
    		
     It was basically used in the past char  In fact, it is used now varchar There are many 
    """
    
     Add :
         After you come to the company, you don't need to consider the field type and field name at all 
         Because the product manager's email to you has all indicated 

    Time type

    • classification

      • date: Specific date 2020-5-4

        datetime: Mm / DD / yyyy HHM / S 2020-5-4 11:11:11

        time: Minutes and seconds 11:11:11

        Year:2020

      • create table student(  
              id int,   
         name varchar(16), 
           born_year year,   
         birth date,    
        study_time time,   
         reg_time datetime);
        
        insert into student values(1,'egon','1880','1880-11-11','11:11:11','2020-11-11 11:11:11');

  Enumeration and collection type

classification

"""
enumeration (enum)   A commonplace
aggregate (set)   More than a multiple-choice
"""

  Specific use

create table user(
	id int,
    name char(16),
    gender enum('male','female','others')
);
insert into user values(1,'jason','male');   normal 
insert into user values(2,'egon','xxxxooo');   Report errors 
#  Enumeration fields   You can only select from the data stored in the later enumeration  


create table teacher(
	id int,
    name char(16),
    gender enum('male','female','others'),
    hobby set('read','DBJ','hecha')
);
insert into teacher values(1,'jason','male','read');   normal 
insert into teacher values(2,'egon','female','DBJ,hecha');   normal 
insert into teacher values(3,'tank','others',' Oysters ');  Report errors 
#  A collection can write only one    But you can't write something without listing 

summary

"""
Field type
Strict mode

constraint condition
    not null
    zerofill
    unsigned
"""

原网站

版权声明
本文为[Right ear needs oil]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/160/202206091209019300.html