当前位置:网站首页>Database day-2
Database day-2
2022-06-09 13:04:00 【Right ear needs oil】
Catalog
mysql Introduction to main documents
Environment variables and system service configuration
Complete syntax for creating tables
Enumeration and collection type
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 tableLast week's content review
Evolution of stored data
"""1 Create documents at will 、 Data formats are also very differentjason|123egon~123tank+1232 Software development catalog specificationThe general location of data storage is defined3 From stand-alone to networking How to operateThe data is stored uniformly and in a fixed formatStore all the data originally stored locally to a place based on network communicationThen all clients go to this place to operate data uniformly"""
The concept of databases
"""
In fact, it is an application based on network communicationThat 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 )、memcacheRelational 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 fileHeader The fields in the first row of the table
Field Field name + Field type
"""
mysql install
"""1 Version of the problemIT 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 modules2 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
\cView 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
# grammarcreate 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 careful1 Field names cannot be repeated in the same table2 Width and constraints are optional ( Write but not write ) The field name and field type are requiredConstraints are written It also supports writing multipleField name 1 type ( Width ) constraint condition 1 constraint condition 2...,create table t5(id); Report errors3 The last line cannot have a commacreate table t6(id int,name char,); Report errors""" Add """# WidthGenerally speaking, it refers to the limitation of data storagecreate table t7(name char); The default width is 1insert into t7 values('jason');insert into t7 values(null); keyword NULLDifferent effects will appear for different versions5.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 you5.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 defaultGuidelines 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 nullcreate table t8(id int,name char not null);"""What is the relationship between width and constraintsWidth is used to limit the storage of dataConstraints 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 dataStrict 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 indicatedTime 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 modeconstraint condition
not null
zerofill
unsigned
"""
边栏推荐
- [Thesis Writing] AI conference citation format, publishing place and publishing house
- AVR与ARM区别以及常用Arduino
- Kubernetes configuration pull private image warehouse
- Make qcombobox drop down a tree structure list
- [STM32] Hal library CRC verification
- 【 NativeScript 】
- [Prometheus summary.observe method]
- 【leetcode周赛记录】第294场周赛记录
- Loki: like Prometheus, but for logs
- Drawing arc text in gdi+
猜你喜欢
随机推荐
树上差分啊
Image matrix transformation in gdi+
【grafana基本使用】
C language stack -- chain stack
ES6基础语法知识
微信小程序-用户授权获取信息
Compress uploaded pictures with JS
[interpretation of the appender source code of logback]
机器学习-学习笔记(二) --&gt; 模型评估与选择
Achieve ceiling effect in wechat applet (smooth and not stuck)
Make qcombobox drop down a tree structure list
[detailed explanation of client list]
Tree diameter (supplement: another DP)
【leetcode周赛记录】第79场双周赛+第295场周赛记录
JVM系列之执行引擎
C language queue -- sequential queue
navicat使用说明
数据库day-2
禅道项目管理流
微信小程序页面之间三种传值方式详解





![[STM32] Hal library CRC verification](/img/6f/51e60fe96c61dd04cae37b4f96954d.png)
