当前位置:网站首页>[MySQL basics]

[MySQL basics]

2022-06-10 15:43:00 CaraYQ

Catalog

Database Overview

Common database concepts

One 、 Memory uses low voltage and high voltage to distinguish 0 and 1 Data storage , So it can't be stored when the power is off , What should we do if we want to store data persistently ? With the help of relevant media

  1. Stored in related files : Pictures are stored in jpg In file , The text is stored in .doc In file ,Java The source code exists .java In file
  2. Complex data is stored in a database
  3. Other media

Persistence (persistence): Save data to a power down storage device for later use . Most of the time , Especially for enterprise applications , Data persistence means saving the data in memory to the hard disk ” curing ”, The implementation process of persistence is mostly accomplished through various relational databases .
The main function of persistence is to store the data in memory in the relational database , Of course, it can also be stored in disk files 、XML In the data file .

Two 、 Why use a database : Database can realize data persistence
3、 ... and 、 The characteristics of database :

  1. The amount of data stored is huge
  2. There are many types of data that can be stored

Four 、 Relevant concepts :

  1. DB: Full name database (Database), It's about storing data “ Warehouse ”, Its essence is a file system . It holds a series of organized data . It is essentially a file that holds data
  2. DBMS: Full name: database management system (Database Management System), It is a kind of large-scale software for manipulating and managing database , For building 、 Use and maintain database , Manage and control the database in a unified way . The user accesses the data in the table in the database through the database management system . Such as MySQL

Scenes in life : You wrote a .doc file , Do you use word To open it ,.doc The document is equivalent to the database here DB,word It is equivalent to the database management system here DBMS

  1. SQL: The full name is structured query language (Structured Query Language), It's a language for communicating with databases .

We use SQL Language coding makes DBMS Help us go to the database DB Do some operations in

5、 ... and 、 Database management system DBMS You can manage multiple databases , Generally, developers will create a database for each application . To save the data of the entity in the application , In general, multiple tables will be created in the database , To save the data of entity users in the program .

MySQL Introduce

One 、MySQL It's an associated database management system , Save the data in different tables , Instead of putting all the data in one big warehouse , This increases speed and flexibility .
Two 、MySQL It can be customized , Adopted GPL(GNU General Public License) agreement , You can modify the source code to develop your own MySQL System .
3、 ... and 、MySQL Support large databases . Can handle large databases with tens of millions of records .32 Bit system table files can support 4GB ,64 The largest table file supported by bit system is 8TB .
Four 、MySQL Use The standard SQL Data language form .
5、 ... and 、 Why choose MySQL:

  1. Open source , Low use cost .
  2. Performance is remarkable , Stable service .
  3. The software is small , Easy to use , And easy to maintain .
  4. Has a long history , Community users are very active , Ask for help when you have problems .
  5. Many Internet companies are using , After the verification of time .

6、 ... and 、Oracle And MySQL Compare

  1. Oracle It is more suitable for large multinational enterprises , Because they are not cost sensitive , But there are higher requirements for performance and safety .
  2. MySQL Because of its small size 、 Fast 、 Low total cost of ownership , A large database that can handle tens of millions of records , Especially open source , Makes many Internet companies 、 Small and medium-sized websites choose MySQL As website database (Facebook,Twitter,YouTube, Alibaba / The ant gold dress , Where are you going? , Meituan takeout , tencent ).

RDBMS And non RDBMS Compare

Relational database RDBMS

One 、 This type of database is the oldest database type , Relational database model is to reduce the complex data structure to simple Binary relationship ( namely Two dimensional tabular form ).
Two 、 Relational database to line (row) And column (column) In the form of data storage . This series of rows and columns is called a table (table), A set of tables form a library (database)
3、 ... and 、 The data records between tables are related (relationship). All kinds of entities in the real world and the relationships between them are represented by relational models . Relational database is a database based on relational model .
Four 、SQL It is the query language of relational database
5、 ... and 、 advantage :

  1. Complex queries : It can be used SQL Statement is convenient to do very complex data query between one table and multiple tables .
  2. Transaction support : So that the data access requirements with high security performance can be realized .

Non relational database RDBMS

One 、 Relational databases have been able to solve most of the problems , In some cases, we need to discard some functions to meet higher requirements . Non relational databases discard the feature of storing rich data , Higher performance has been achieved
Two 、MySQL Operating relational databases ,NoSQL Operate on non relational databases

Key database

Key value database through Key-Value Key value to store data , among Key and Value It can be a simple object , It can also be a complex object .Key As a unique identifier , The advantage is that the search speed is fast , In this respect, it is obviously better than relational database , The disadvantage is that you can't use conditional filtering like a relational database ( such as WHERE), If you don't know where to find the data , You have to traverse all the keys , This will consume a lot of computation . The typical usage scenario of key value database is as memory cache . Redis Is the most popular key value database .

Document database

This kind of database can store and obtain documents , It can be XML、JSON Equiform . In a database, a document is the basic unit for processing information , A document is a record . Documents stored in the document database , It is equivalent to that stored in the key value database “ value ”.MongoDB Is the most popular document database . Besides , also CouchDB etc. .

Search engine database

Although relational database adopts index to improve retrieval efficiency , However, the efficiency of full-text indexing is low . Search engine database is a data storage form applied in the field of search engine , Because search engines crawl a lot of data , And stored in a specific format , In this way, the best performance can be guaranteed when searching . The core principle is “ Inverted index ”.
Typical products :SolrElasticsearchSplunk etc. .

Columnar database

A column database is a database relative to a row store ,OracleMySQLSQL Server And so on the database all uses the line type storage (Row-based), The columnar database is to store data into the database according to columns , The advantage of this is that it can reduce the system greatly I/O, Suitable for distributed file systems , The disadvantage is that the function is relatively limited . Typical products :HBase etc. .
Suppose we want to query the information of some fields of a record in the database , For example, I just want to check the age of Zhang San , I don't need to know his gender 、 Professional and so on , If you use a database based on row storage , All the data of Zhang San will be loaded into memory during query , Will load useless information , So that means we have done a lot of redundant IO, Low performance . But if the columnar database is used to store data , Then I only need to query the column of the field you want .

If there is 100 personal , There is only one person 20 A field , Is it more efficient to use row storage ?

Graphic database

The data structure of graph is used to store entities ( object ) The relationship between , The most typical example of graphical database is the relationship between people in social networks , The data model is mainly based on nodes and edges ( Relationship ) To achieve , The feature is that it can efficiently solve complex relationship problems
Graphic database as the name suggests , It is a database that stores graphical relationships . It uses the data structure of graph to store entities ( object ) The relationship between . Relational data is used to store data with explicit relationships , But for the data storage of complex relationships, it is not enough . Such as the relationship between characters in social networks , If you use a relational database, it is very complex , Using a graphics database will be very simple . Typical products :Neo4J、InfoGrid etc. .

Relational database design rules

One 、 The typical data structure of relational database is data table , The composition of these data tables is structured
Two 、 Put the data in the table , Put the watch in the library
3、 ... and 、 There can be multiple tables in a database , Every watch has a name , To identify yourself . Table names are unique .
Four 、 Table has some characteristics , These properties define how data is stored in tables , similar Java and Python in “ class ” The design of the .

surface 、 Record 、 Field

One 、 The relationship between tables is expressed in E-R Model to describe .E-R(entity-relationship, Entity - contact ) There are three main concepts in the model : Entity set 、 attribute 、 Contact set .

Entity set : surface
attribute : Fields in the table
Contact set : The relationship between records in a table and records in another table

Two 、 A set of entities (class) Corresponding to a table in the database (table), An entity (instance) It corresponds to a row in the database table (row), Also known as a record (record). An attribute (attribute) Corresponds to a column in the database table (column), Also known as a field (field).

A relation corresponding to the operation of a database in a programming language , This relationship we call ORM mapping
ORM thought (Object Relational Mapping) reflect :
A table in the database <——> Java or Python A class in
A piece of data in the table <——> An object in a class ( Or entity )
A column in the table <——> A field in a class 、 attribute (field)

 Insert picture description here

The relationship between tables

One 、 The data records between tables are related (relationship). All kinds of entities in the real world and the relationships between them are represented by relational models .
Two 、 Four kinds of : One to one connection 、 One to many connection 、 Many to many connection 、 Self quoting

One to one connection (one-to-one)

One 、 One to one connection : surface A A record in the corresponding table B One of the records
Two 、 There are not many applications in the actual development , Because one-to-one can be created as a table .

give an example : Design a student list : Student number 、 full name 、 Phone number 、 class 、 Is don't 、 Id card number 、 Home address 、 Native place 、 Emergency contact 、… There are so many fields , We can split it into two tables , The records of the two tables are one-to-one correspondence .
Basic information table ( Frequently used information ): Student number 、 full name 、 Phone number 、 class 、 Is don't
File information table ( Infrequent information ): Student number 、 Id card number 、 Home address 、 Native place 、 Emergency contact 、…
If you don't dismantle it , Every time we query, we will load many unnecessary fields , For example, infrequently used information is often loaded in , After the disassembly, I will query every time ( No ) Frequently used information , Reduce the loading of redundant information , Reduce IO, Improve performance

3、 ... and 、 Two principles of table building :
The foreign key is unique : Primary key of master table and foreign key of slave table ( only ), Form the main foreign bond relationship , The foreign key is unique .
The foreign key is the primary key : Primary key of master table and primary key of slave table , Form the main foreign bond relationship .

One-to-many relation (one-to-many)

One 、 surface A A record in the corresponding table B Multiple records in
Two 、 Common instance scenarios : Customer and order forms , Classification table and commodity table , Department tables and staff tables .

give an example :
The employee table : Number 、 full name 、…、 Department
Departmental table : Number 、 name 、 brief introduction
The Department table stores the records of each department , There can be more than one employee in a department , That is, one record corresponds to multiple employees

3、 ... and 、 One to many tabulation principle : From table ( In many ways ) Create a field , The field points to the main table as a foreign key ( a party ) Primary key of

Many to many (many-to-many)

One 、 To represent a many to many relationship , You must create a third table , This table is often called a join table , It divides many to many relationships into two one to many relationships . Insert the primary keys of both tables into the third table .
Two 、 give an example

  1. Student - Course
    Student information sheet : One line represents a student's information ( Student number 、 full name 、 Phone number 、 class 、 Is don't …)
    Course information sheet : One line represents the information of a course ( Course number 、 Teaching teacher 、 brief introduction ……)
    Course selection information table : A student can take multiple courses , A course can be chosen by more than one student
  2. product - Order :“ Order ” Table and “ product ” Tables have a many to many relationship , This relationship is achieved through a relationship with “ The order details ” A table is defined by establishing two one to many relationships . One order can have multiple products , Each product can appear in multiple orders .
    Product list :“ product ” Each record in the table represents a product .
    The order sheet :“ Order ” Each record in the table represents an order .
    Order details : Each product can be combined with “ Order ” Multiple records in the table correspond to , That is, it appears in multiple orders . An order can be made with “ product ” Multiple records in the table correspond to , That is, it contains multiple products .
  3. user - role
    Many to many relationship table building principle : You need to create a third table , At least two fields in the middle table , These two fields are used as foreign keys to each other's primary keys .

Self quoting

Quote yourself , The following table :
 Insert picture description here

MySQL Environment building

MySQL The uninstall

Step one : stop it MySQL service

Before uninstalling , First stop MySQL8.0 Service for . Press on the keyboard “Ctrl + Alt + Delete” Composite key , open “ Task manager ” Dialog box , Can be in “ service ” List found “MySQL8.0” Service for , If now “ Running ” state , You can right-click Services , choice “ stop it ” Option stop MySQL8.0 Service for , As shown in the figure .
 Insert picture description here

Step two : Software uninstall

The way 1: Via control panel

uninstall MySQL8.0 Your application can be directly in the same way as other desktop applications “ Control panel ” choice “ Uninstall program ”, And find... In the program list MySQL8.0 Server program , Double click uninstall directly , As shown in the figure .
 Insert picture description here
Delete in this way , The data in the data directory will not be deleted .

The way 2: adopt 360 Or software such as computer manager

A little

The way 3: Uninstall through the uninstall function provided by the installation package

You can also use the installation wizard to MySQL8.0 Uninstall the server program .

  1. Double click the downloaded... Again mysql-installer-community-8.0.26.0.msi file ( That is, the software installation package ), Open the setup wizard . The setup wizard will automatically detect installed MySQL Server program .
     Insert picture description here
    And then execute :
     Insert picture description here
  2. Select the to uninstall MySQL Server program , single click “Remove”( remove ), You can uninstall .
     Insert picture description here
  3. single click “Next”( next step ) Button , Confirm uninstall .
     Insert picture description here
  4. A window will pop up to select whether to remove the data directory at the same time . If you want to delete MySQL Data in the server , Then check “Remove the data directory”, As shown in the figure .
     Insert picture description here
  5. Perform the uninstall . single click “Execute”( perform ) Button to unload .
     Insert picture description here
  6. Uninstall complete . single click “Finish”( complete ) button . If you want to uninstall at the same time MySQL8.0 Installation wizard for , Check “Yes,Uninstall MySQL Installer” that will do , As shown in the figure .
     Insert picture description here

Step three : Cleaning of residual files

One 、 If the installation is not successful again , You can uninstall and clean up the residual files before installing .

  1. Service catalog :mysql The installation directory of the service
  2. Data directory : Default in C:\ProgramData\MySQL
    If you have specified the data directory separately , Just find your own data directory and delete it .

Be careful : Please make data backup before unloading

Two 、 After the operation , Need to restart the computer , Then install it . If the installation still fails , You need to continue with the following steps 4.

Step four : Clean up the registry ( Choose to do )

One 、 If you did the previous steps , The installation failed again , Then you can clean the registry .
Two 、 How to open the registry editor : In the system's search box (win+r) Input in regedit

HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Services\Eventlog\Application\MySQL service   Directory delete 
HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Services\MySQL service   Directory delete 
HKEY_LOCAL_MACHINE\SYSTEM\ControlSet002\Services\Eventlog\Application\MySQL service   Directory delete 
HKEY_LOCAL_MACHINE\SYSTEM\ControlSet002\Services\MySQL service   Directory delete 
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Eventlog\Application\MySQL Service directory delete 
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\MySQL Service deletion 

Be careful : In the registry ControlSet001,ControlSet002, Is not necessarily 001 and 002, May be ControlSet005006 And so on

Step five : Delete the environment variable configuration

One 、 find path environment variable , Put it all about mysql Delete the environment variable of , Remember not to delete all . for example : Delete D:\develop_tools\mysql\MySQLServer8.0.26\bin; This part
 Insert picture description here

MySQL The download 、 install 、 To configure

One 、MySQL Of 4 The big version

  1. MySQL Community Server Community version , Free open source , Free download , But no official technical support , Suitable for most ordinary users .
  2. MySQL Enterprise Edition Enterprise version , Pay for , Can't download online , You can try 30 God . It provides more functions and more complete technical support , It is more suitable for enterprise customers with high requirements for database function and reliability .
  3. MySQL Cluster Cluster version , Free open source . It is used to set up cluster servers , You can put a few MySQL Server Encapsulate into a Server. It needs to be used on the basis of community version or enterprise version .
  4. MySQL Cluster CGE Advanced clustering , Pay for .

Two 、 Used in this course 8.0.26 edition .
3、 ... and 、 Officials also provide MySQL Workbench(GUITOOL) One for MySQL Designed graphical interface management tool .MySQLWorkbench It's divided into two versions , Namely Community Edition (MySQL Workbench OSS)、 Commercial version (MySQL WorkbenchSE).

download

One 、 Download address : Official website
Two 、 Open the website , Click on DOWNLOADS, then , Click on MySQL Community(GPL) Downloads
 Insert picture description here
3、 ... and 、 Click on MySQL Community Server
 Insert picture description here
Four 、 stay General Availability(GA) Releases Select the appropriate version
 Insert picture description here
Windows Two installation files are provided under the platform :MySQL Binary distribution (.msi The installation files ) And installation free version (.zip Compressed files ). In general , Binary distributions should be used , Because this version provides a graphical installation wizard process , Easier to use than other distributions , You don't need other tools to start to run MySQL.
Here it is Windows It is recommended to download MSI Erection sequence ; Click on Go to Download Page Download it
5、 ... and 、Windows Under the MySQL8.0 There are two installers installed

  1. mysql-installer-web-community-8.0.26.0.msi Download program size :2.4M; Networking installation components are required during installation .
  2. mysql-installer-community-8.0.26.0.msi Download program size :450.7M; Offline installation during installation, i.e
    can . recommend .
     Insert picture description here
    If installed MySQL5.7 Version! , choice Archives You can select the historical version in it , Then choose MySQL5.7 The corresponding version of . Download the latest MySQL5.7.34 edition .

install

MySQL When the download is complete , Find the download file , Double click to install , The specific operation steps are as follows .

  1. Double-click the downloaded mysql-installer-community-8.0.26.0.msi file , Open the setup wizard .
  2. open “Choosing a Setup Type”( Choose the installation type ) window , It lists 5 Installation types , Namely Developer Default( Default installation type )Server only( Just as a server )Client only( Just as a client )Full( Completely installed )Custom( Custom installation ). Choose here “Custom( Custom installation )” Type button , single click “Next( next step )” Button .
     Insert picture description here
  3. open “Select Products” ( Choose products ) window , You can customize the list of products to be installed . for example , choice “MySQL Server 8.0.26-X64” after , single click “→” Add a button , You can choose to install MySQL The server , As shown in the figure . Adopt a general method , You can add other products you need to install .
     Insert picture description here
    At this point, if you directly “Next”( next step ), The installation path of the product is the default . If you want to customize the installation directory , You can select the corresponding product , Then it will appear below “Advanced Options”( Advanced options ) Hyperlinks for .
     Insert picture description here
    single click “Advanced Options”( Advanced options ) The installation directory selection window will pop up , As shown in the figure , At this point, you can set it separately MySQL Server program installation directory and data storage directory . If not set , By default, they are in C Discoid Program Files Contents and ProgramData Catalog ( This is a hidden Directory ). If you customize the installation directory , Please avoid “ chinese ” Catalog . in addition , It is recommended that the service directory and data directory be stored separately .
     Insert picture description here
  4. After selecting the product to install in the previous step , single click “Next”( next step ) Enter the confirmation window , As shown in the figure . single click “Execute”( perform ) Button to start installation .
     Insert picture description here
  5. After the installation is completed, please wait “Status”( state ) Below the list will be displayed “Complete”( installation is complete ), As shown in the figure .
     Insert picture description here

MySQL8.0 To configure

MySQL After installation , You need to configure the server . The specific configuration steps are as follows .

  1. In the last step of the previous section , single click “Next”( next step ) Button , You can enter the product configuration window .
     Insert picture description here
  2. single click “Next”( next step ) Button , Get into MySQL Server type configuration window , As shown in the figure . Generally, the default port number is selected 3306
     Insert picture description here
    among ,“Config Type” Option is used to set the type of server . Click the bottom triangle button to the right of the option , You can view it 3 An option , As shown in the figure .
     Insert picture description here
    Development Machine( Developing machines ): This option represents a typical personal desktop workstation . At this point, multiple applications need to run on the machine , that MySQL The server will use the least system resources
    Server Machine( The server ) : This option represents the server ,MySQL The server can run with other server applications , for example Web The server etc. .MySQL The server is configured with an appropriate proportion of system resources .
    Dedicated Machine( Dedicated server ) : This option represents run only MySQL Servers served .MySQL The server is configured to use all available system resources .
  3. single click “Next”( next step ) Button , Open the set authorization mode window . among , The options above are MySQL8.0 New ways of Authorization , use SHA256 Basic cryptographic methods ; The following options are traditional authorization methods ( Retain 5.x Version compatibility ).
     Insert picture description here
  4. single click “Next”( next step ) Button , Open setup server root Super administrator password window , As shown in the figure , You need to enter the same login password twice . It can also be done through “Add User” Add other users , When adding other users , You need to specify a user name 、 The user name is allowed on which computer / Which hosts log in , You can also specify user roles, etc . Users will not be added here , User management in MySQL Advanced features .
     Insert picture description here
  5. single click “Next”( next step ) Button , Open the set server name window , As shown in the figure . The service name will appear in Windows In the list of services , You can also use the service name in the command line window to start and stop the service . This article sets the service name to “MySQL80”. If you want to start the self starting service , You can also check “Start the MySQL Server at System Startup” Options ( recommend ).
    Here is how to run the service ? You can choose “Standard System Account”( Standard system users ) perhaps “Custom User”( Custom user ) One of them . The former is recommended here .
     Insert picture description here
  6. Click click “Next”( next step ) Button , Open the confirm settings server window , single click “Execute”( perform ) Button
     Insert picture description here
  7. Complete the configuration , As shown in the figure . single click “Finish”( complete ) Button , The configuration of the server can be completed .
     Insert picture description here
  8. If there are other products that need to be configured , You can choose other products , Then continue to configure . without , Direct selection “Next”( next step ), Directly complete the whole installation and configuration process .
     Insert picture description here
  9. End installation and configuration .
     Insert picture description here

MySQL5.7 install 、 To configure

One 、 install : The installation process of this version is the same as the above process, except that the version number is different , Other links are the same . So we omit MySQL5.7.34 Screenshot of version installation .
Two 、 To configure : Configuration phase and MySQL8.0 The version is slightly different . In most cases, choose directly “Next” that will do , It does not affect the finishing and use . Configuration here MySQL5.7 when , Focus on : With the previously installed MySQL8.0 You cannot use the same port number .

Installation failure problem

One 、 problem 1: Unable to open MySQL8.0 Software installation package or failure during installation , How to solve ?
Running MySQL8.0 Before installing the package , Users need to ensure that... Is installed in the system .Net Framework Related software , If this software is missing , Will not install properly MySQL8.0 Software .
 Insert picture description here
Solution : To here download Microsoft .Net Framework 4.5 And after installation , Then go install MySQL. in addition , Also make sure Windows Installer normal setup .windows Installation on mysql8.0 The operating system needs to be installed in advance Microsoft Visual C++ 2015-2019.
 Insert picture description here
 Insert picture description here
The solution is still to Microsoft official website Download the corresponding environment
Two 、 Unload and reload MySQL Failure ?
The problem is usually due to MySQL When uninstalling , Not completely clear the relevant information .
Solution : Delete the previous installation directory . If the service installation directory has not been specified separately in the previous installation , The default installation directory is C:\Program Files\MySQL, Completely delete the directory . At the same time to delete MySQL Of Data Catalog , If the data directory has not been specified separately in the previous installation , The default installation directory is C:\ProgramData\MySQL, This directory is generally hidden . After deleting , Just reinstall .
3、 ... and 、 How to be in Windows The system deletes the previously uninstalled clean MySQL List of services ?
In system “ Search box ” Input in “cmd”, Press “Enter”( enter ) Key confirmation , The command prompt interface pops up . Then input “sc delete MySQL service name ”, Press “Enter”( enter ) key , You can completely delete the remaining MySQL Yes .

Configure environment variables

If you don't configure MySQL environment variable , You can't type... Directly on the command line MySQL Login command . Here's how to configure MySQL Environment variables of :

  1. Right click on the desktop 【 This computer 】 Icon , Choose... From the shortcut menu that pops up 【 attribute 】 The menu command .
  2. open 【 System 】 window , single click 【 Advanced system setup 】 link .
  3. open 【 System attribute 】 Dialog box , choice 【 senior 】 tab , And then click 【 environment variable 】 Button .
  4. open 【 environment variable 】 Dialog box , Select... In the system variable list path Variable .
  5. single click 【 edit 】 Button , stay 【 Edit environment variables 】 In the dialog box , take MySQL Application's bin Catalog (C:\ProgramFiles\MySQL\MySQL Server 8.0\bin) Add to variable value , Separate it from other paths with semicolons .
  6. Add after completion , single click 【 determine 】 Button , This completes the configuration path Variable operation , Then you can directly enter MySQL Command to log in to the database .

Service startup 、 Sign in

Start and stop of service

One 、MySQL After installation , The server process needs to be started , Otherwise, the client cannot connect to the database .
Two 、 In the previous configuration process , Have already put MySQL Installed as Windows service , And check when Windows start-up 、 When it stops ,MySQL It also starts automatically 、 stop it .

Use GUI tools

  1. open windows service
    The way 1: Computer ( Right click )→ management ( Click on )→ Services and Applications ( Click on )→ service ( Click on )
    The way 2: Control panel ( Click on )→ Systems and security ( Click on )→ Management tools ( Click on )→ service ( Click on )
    The way 3: The task bar ( Right click )→ Start task manager ( Click on )→ service ( Click on )
    The way 4: single click 【 Start 】 menu , Type in the search box “services.msc”, Press Enter Key confirmation
  2. find MySQL80( Right click )→ To start or stop ( Click on )
     Insert picture description here

Use command line tools

#  start-up  MySQL  The service command :
net start MySQL service name 
#  stop it  MySQL  The service command :
net stop MySQL service name 

 Insert picture description here
explain :

  1. start and stop The following service name should be consistent with the service name specified during previous configuration .
  2. If when you enter a command , Tips “ Denial of service ”, Please open the command prompt interface as the system administrator and try again .

Login and exit of the built-in client

When MySQL After service startup , You can log in through the client MySQL database . Be careful : Confirm that the service is on .

MySQL It comes with its own client

The start menu → All the procedures → MySQL → MySQL 8.0 Command Line Client
 Insert picture description here
explain : Is limited to root user

Windows Command line

Format :mysql -h Host name -P Port number -u user name -p password
give an example :mysql -h localhost -P 3306 -u root -pabc123 # Here I set root The user's password is abc123
explain :

  1. -p There must be no space between and password , There may or may not be spaces between other parameter names and parameter values . Such as :mysql -hlocalhost -P3306 -uroot -pabc123
  2. The writing order is not required
  3. It is recommended to enter the password on the next line , Keep it safe
mysql -h localhost -P 3306 -u root -p
Enter password:****
  1. The client and server are on the same machine , So the input localhost perhaps IP Address 127.0.0.1. meanwhile , Because it is connected to this machine : -hlocalhost You can omit , If the port number has not been modified :-P3306 You can omit it , Abbreviation :
mysql -u root -p
Enter password:****

After successful connection , About MySQL Server Service version information , And the number of connections id identification . It can also be done on the command line through c:\> mysql -V or c:\> mysql --version obtain MySQL Server Service version information . Or after login , adopt mysql> select version(); View current version information .

Log out

exit or quit

MySQL Demonstrate the use of

Launch and log in mysql After use

View all databases

Format :show databases;
 Insert picture description here
explain :

  1. information_schema yes MySQL The database of the system , The main preservation is MySQL System information of database server , For example, the name of the database 、 The name of the data table 、 Field name 、 Access rights 、 Data files The folder and the folder used by the system , wait
  2. performance_schema yes MySQL The database of the system , Can be used to monitor MySQL Various performance indexes .
  3. sys database yes MySQL The database of the system , The main function is to show... In a more understandable way MySQL Various performance indexes of database server , Help system administrators and developers monitor MySQL Technical performance .
  4. mysql The database holds MySQL System information required by the database server to run , Such as data folders 、 Currently in use Character set 、 Constraint check information , wait

Create your own database

Format :create database Database name ;. for example , establish dbtest1 database :create database dbtest1;, The name cannot be the same as an existing database .

Using a database

Format :use Database name ;. for example , Use dbtest1 database :use dbtest1;

explain : If not used use sentence , The following operations on the database do not add “ Data name ” The limit of , Then it will be reported. “ERROR 1046 (3D000): No database selected”( No database selected ), Use up use After statement , If the next SQL They are all aimed at a database operation , Then don't repeat use 了 , If you want to operate on another database , Then we have to re use. As shown in the following figure, create a table directly after creating a database , Not used use Using a database
 Insert picture description here

View all tables in a library

Format :show tables from Database name ;

Create a new table

create table  The name of the table ( 
	 Field name   data type ,
	 Field name   data type 
);

For example, create an employee table :

create table employees(
	id int,
	name varchar(20) # The longest name is no more than 20 Characters  
);

explain : If it is the last field , You don't have to add a comma after it , Because the comma is used to separate each field .

View the data of a table

Format :select * from Database table name ;. for example , View the data of the employee table :select * from employees;

Add a record to the table

One 、 Format :insert into The name of the table values( List of values );. for example , Add two records to employees In the table :insert into employees values(1,'cara');.
Two 、 But if 5.7 The version is written in Chinese :insert into employees values(1,' Zhang San '); insert into employees values(2,' Li Si '); Will report a mistake :

mysql> insert into employees values(1,' Zhang San ');
ERROR 1366 (HY000): Incorrect string value: '\xD5\xC5\xC8\xFD' for column 'name' at row 1
mysql> insert into employees values(2,' Li Si ');
ERROR 1366 (HY000): Incorrect string value: '\xC0\xEE\xCB\xC4' for column 'name' at row 1

This is a character set problem , Because the character set you are using now is the default latin, No utf-8, Unable to recognize Chinese .
3、 ... and 、 The following code can view the database default character set :

show variables like 'character_%';# View the default character set used by the database 
show variables like 'collation_%';# View character sorting comparison rules 

 Insert picture description here
 Insert picture description here
Four 、 Solution : Change the default character set

  1. modify MySQL Under the data directory of my.ini The configuration file :
[mysql] # Around the 63 Row or so , Add under :
...
default-character-set=utf8 # Default character set 
[mysqld] #  In about 76 Row or so , Add under 
...
character-set-server=utf8
collation-server=utf8_general_ci

Be careful : It is recommended to modify the configuration file to use notepad++ And other advanced text editors , After opening and modifying with software such as Notepad, the file code may be changed to “ contain BOM head ” The coding , Thus, the service restart fails .

  1. restart MySQL
  2. Check if the setting is successful , The following configuration succeeded , Then we can create a new database 、 Create a new data table , Then add the data containing Chinese , If you have a previous database 、 The data table is still used latin, Cannot add Chinese data .
     Insert picture description here

5、 ... and 、 stay MySQL 8.0 Before the release , The default character set is latin1,utf8 The character set points to utf8mb3. Website developers often change the code to utf8 Character set . If you forget to change the default code , There will be a problem of garbled code . from MySQL 8.0 Start , The default code of the database is changed to utf8mb4 , Thus, the above garbled code problem is avoided .

View the table creation information

Format :show create table The name of the table \G. for example , see employees Table creation details :show create table employees\G

View database creation information

Format :show create database Database name \G. for example , see dbtest1 Database creation details :show create database dbtest1\G
 Insert picture description here

Delete table

Format :drop table The name of the table ;. for example , Delete student table :drop table student;

Delete database

Format :drop database Database name ;. for example , Delete atguigudb database :drop database atguigudb;

MySQL Directory structure and source code

Main directory structure

MySQL Directory structure of explain
bin Catalog all MySQL The executable of . Such as :mysql.exe
MySQLInstanceConfig.exe Database configuration wizard , What appears during installation
data Catalog The directory where the system database is located
my.ini file MySQL The main configuration file for
c:\ProgramData\MySQL\MySQL Server 8.0\data\ The directory of the database created by the user

MySQL Source code acquisition

First , You have to enter MySQL Download Interface . Here you don't choose to use the default “Microsoft Windows”, But through the drop-down bar , find “Source Code”, In the following operating system version , choice Windows(Architecture Independent), Then click download . Next , Unzip the downloaded compressed file , We got it MySQL Source code . The source code can be opened and viewed with Notepad , If you have C++ Development environment of , You can also open and view... In the development environment .MySQL yes C++ Developed by , Let me briefly introduce the composition of the source code :

  1. sql The subdirectory is MySQL Core code ;
  2. libmysql Subdirectories are client programs API;
  3. mysql-test Subdirectories are test tools ;
  4. mysys Subdirectories are operating system related functions and auxiliary functions ;

Common problems and solutions

root User password forgotten , Reset operation

Solution :

  1. Through task manager or service management , Turn off the mysqld( Service process )
  2. From the command line + Special parameters on mysqld:mysqld -- defaults-file="D:\ProgramFiles\mysql\MySQLServer5.7Data\my.ini" --skip-grant-tables
  3. here ,mysqld The service process has been opened . And no permission check is required
  4. mysql -uroot No password login server . Start another client for
  5. Modify the permission table :
use mysql;
update user set authentication_string=password(' New password ') where user='root' and Host='localhost';
flush privileges;
  1. Through task manager , Turn off the mysqld Service process .
  2. Again through service management , open mysql service .
  3. You can log in with the new password after modification .

mysql Order newspaper “ Not an internal or external command ”

hold mysql Installation directory bin Directory configuration to environment variables path in .

error error: Operate tables and data without selecting a database

Report errors :ERROR 1046 (3D000): No database selected
Solution :

  1. Is the use of USE Database name ; sentence , In this way, the following statements will operate on the database by default
  2. That is, all table objects are preceded by database .

The character set problem of the command-line client

mysql> INSERT INTO t_stu VALUES(1,' Zhang San ',' male ');
ERROR 1366 (HY000): Incorrect string value: '\xD5\xC5\xC8\xFD' for column 'sname' at
row 1

reason : The server thinks your client's character set is utf-8, In fact, the character set of your client is GBK.
 Insert picture description here
See all character sets :SHOW VARIABLES LIKE 'character_set_%';
 Insert picture description here
Solution : Set the client character set of the current connection :SET NAMES GBK;. If you're using cmd:
 Insert picture description here

Modify the character encoding of databases and tables

See above

原网站

版权声明
本文为[CaraYQ]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/161/202206101526281676.html