[MySQL Beginner Series 2]: Teach you how to get started with MySQL - database and data table operations

If you are a novice who has just started to learn MySQL, this article will provide you with some practical introductory knowledge and skills to help you get started quickly.
[MySQL Beginner Series 1]: Teach you how to get started with MySQL.
We have already talked about the installation of mysql before. This article will take windows as an example to introduce the operation of MySQL database and data table (addition, deletion, modification and query).

1. Overview

After the MySQL installation is complete, the next step is to create a database and create a data table.

Two, MySQL database operation

After MySQL is installed, you can perform database-related operations. At this time, there is no database for our own use, so we have to create a new database of our own first.

2.1 Create a database

grammar:

CREATE DATABASE [IF NOT EXISTS] <数据库名>
[[DEFAULT] CHARACTER SET <字符集名>] 
[[DEFAULT] COLLATE <校对规则名>];

The syntax is explained as follows:

1. <database name>: the name of the database to be created, which cannot start with a number.
2. IF NOT EXISTS: judge before creating the database, and only execute the creation statement when the database does not exist.
3. [DEFAULT] CHARACTER SET: Specify the character set of the database. The purpose is to avoid garbled characters in the data stored in the database.
4. [DEFAULT] COLLATE: Specify the default collation rules for the character set.

Let's take an example. Now there is a bookstore. To store book-related information, create a new database and name it "bookstore":

CREATE DATABASE IF NOT EXISTS bookstore
DEFAULT CHARACTER SET utf8mb4
DEFAULT COLLATE utf8mb4_unicode_ci;

If you don't want to set some properties, you can directly use the following simple statement:

CREATE DATABASE bookstore;

when see

“Query OK, 1 row affected (0.32 sec);”

In the prompt, "Query OK" means the command is executed successfully, and "0.32 sec" means the execution time.

2.2 View all databases

practical grammar

SHOW DATABASES [LIKE 'database name'];

For example:
insert image description here
the first one is the bookstore we just created

2.3 Modify the database

  • grammar:
ALTER DATABASE [数据库名] { 
[ DEFAULT ] CHARACTER SET <字符集名> |
[ DEFAULT ] COLLATE <校对规则名>}

The following is an example SQL statement for modifying the default character set and collation rules of a database named exampleDB

ALTER DATABASE exampleDB CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

This SQL statement will modify the default character set and collation rules of exampleDB to utf8mb4 and utf8mb4_unicode_ci, while retaining the original data in the database.

  • You can also rename the database:
ALTER DATABASE exampleDB RENAME TO newDBName;

Change the database named exampleDB to be named newDBName. It should be noted that during the process of modifying the database name, you need to close all connections to the database, otherwise an error will be reported.

2.4 Delete the database

  • grammar
DROP DATABASE [ IF EXISTS ] <数据库名>

where database_name represents the name of the database to be deleted. If IF EXISTS is specified, when deleting a database that does not exist, no error will be reported but silently returned.

3. MySQL data table operation

The data table is an important part of the database. We have introduced how to create a new database above. The table-related operations are described below.

3.1 Learn how to create tables

  • grammar
CREATE TABLE <表名> ([表定义选项])[表选项][分区选项];

CREATE TABLE table_name (
    column1 datatype [constraint],
    column2 datatype [constraint],
    column3 datatype [constraint],
    ...
    PRIMARY KEY (one or more columns)
);

where table_name represents the name of the table to be created. column1, column2, column3, etc. represent the column names in the table, and datatype represents the data type of the column. [constraint] can be omitted if no constraints need to be set. PRIMARY KEY is used to specify the primary key in the table, and one or more columns may need to be set as the primary key to ensure the uniqueness of the data in the table.

  • For example:
    Create a new data table named "books", including book number, book name, author and price:
CREATE TABLE books(
  id INT(11) NOT NULL AUTO_INCREMENT,
  title VARCHAR(255) DEFAULT NULL,
  author VARCHAR(255) DEFAULT NULL,
  price DECIMAL(10,2) DEFAULT NULL,
  PRIMARY KEY(id)
);

3.2 Learn how to drop tables

  • grammar
DROP TABLE [IF EXISTS] table_name;

where table_name represents the name of the table to drop. If IF EXISTS is specified, when deleting a table that does not exist, no error will be reported but silently returned.

  • for example:
删除名为 users 的数据库表
DROP TABLE users;

This SQL statement deletes the database table named users and all data in it.

3.3 Learn how to modify the table structure

  • grammar
ALTER TABLE <表名> [修改选项]ALTER TABLE table_name 
    ADD [COLUMN] column_name data_type [NULL | NOT NULL] [DEFAULT default_value] [AFTER | FIRST column_name],
    DROP [COLUMN] column_name,
    MODIFY [COLUMN] column_name new_data_type [NULL | NOT NULL] [DEFAULT default_value] [FIRST | AFTER column_name],
    RENAME [COLUMN] old_column_name TO new_column_name,
    RENAME TO new_table_name;

There are many parameters. Among them, ADD can add a new column, DROP can delete an existing column, MODIFY can modify the data type and other attributes of an existing column, and RENAME can rename an existing column or the entire table.

  • for example:
添加一个新列 age 到一个名为 users 的表中
ALTER TABLE users ADD COLUMN age INT(11) AFTER email;
删除一个名为 age 的列
ALTER TABLE users DROP COLUMN age;
修改一个名为 username 的列的数据类型和默认值
ALTER TABLE users MODIFY COLUMN username VARCHAR(100) NOT NULL DEFAULT 'anonymous' AFTER id;
将一个名为 name 的列重命名为 full_name
ALTER TABLE users RENAME COLUMN name TO full_name;
将一个名为 users 的表重命名为新名称 customers
ALTER TABLE users RENAME TO customers;

3.4 Data type introduction and use of time data types such as DATE, TIME, DATETIME and TIMESTAMP

In SQL, there are many different data types, including numeric types, character types, datetime types, and more. Some common data types are briefly described below:

  • INT/ INTEGER: integer type
  • VARCHAR: variable-length string type
  • CHAR: Fixed-length string type
  • TEXT: text string type
  • DECIMAL/ NUMERIC: Fixed-point number type
  • FLOAT/ DOUBLE: floating point type
  • DATE: date type, only accurate to the date
  • TIME: time type, only accurate to hours, minutes and seconds
  • DATETIME: date time type, accurate to milliseconds
  • TIMESTAMP: Timestamp type, accurate to seconds

The following are sample SQL statements using different time data types:

  • DATEStore date data using

    CREATE TABLE sales (
        id INT(11) NOT NULL AUTO_INCREMENT,
        customer_id INT(11) NOT NULL,
        order_date DATE NOT NULL,
        total_amount DECIMAL(10,2) NOT NULL,
        PRIMARY KEY (id)
    );
    

    order_dateThe column is specified as DATEtype so it is only accurate to date, not time.

  • TIMEStore time data using

    CREATE TABLE employees (
        id INT(11) NOT NULL AUTO_INCREMENT,
        name VARCHAR(50) NOT NULL,
        start_time TIME NOT NULL,
        PRIMARY KEY (id)
    );
    

    start_time 列被指定为TIME` type, so it is only accurate to the hour, minute and second, not including the date.

  • DATETIMEStore datetime data using

    CREATE TABLE log (
        id INT(11) NOT NULL AUTO_INCREMENT,
        access_time DATETIME NOT NULL,
        user_id INT(11) NOT NULL,
        PRIMARY KEY (id)
    );
    

    access_time 列被指定为DATETIME` type, so it includes date and time, accurate to milliseconds.

  • TIMESTAMPStore timestamped data using

    CREATE TABLE bookings (
        id INT(11) NOT NULL AUTO_INCREMENT,
        checkin_time TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
        checkout_time TIMESTAMP NOT NULL DEFAULT '1970-01-01 00:00:01',
        room_id INT(11) NOT NULL,
        PRIMARY KEY (id)
    );
    

    checkin_time checkout_time 列都被指定为TIMESTAMP 类型,因此它们包括日期和时间,精确到秒。其中,checkin_time 的默认值被设置为当前时间戳,checkout_time 的默认值被设置为'1970-01-01 00:00:01'`, representing the minimum timestamp value.

It should be noted that in different database management systems, the time data type may be different, such as the difference between DATETIMEand TIMESTAMP. Also, careful consideration needs to be given to how time zones, leap seconds, etc. are handled. In actual use, it is recommended to refer to relevant documents and standards, and follow best practices.

3.5 How to use SQL constraints to protect data integrity

In SQL, you can use constraints (Constraint) to limit or protect the integrity of the data in the table. These constraints include column-level constraints and table-level constraints.

Column-level constraints are constraints on individual columns, such as NOT NULL, UNIQUE, PRIMARY KEY, and FOREIGN KEY constraints. Table-level constraints are constraints on multiple columns, such as CHECK constraints.

Here are some common SQL constraints and how they are used to protect data integrity:

  • NOT NULLConstraints: Used to ensure that the values ​​in a column are not null.

    CREATE TABLE Users (
        ID INT NOT NULL,
        FirstName VARCHAR(50) NOT NULL,
        LastName VARCHAR(50) NOT NULL,
        Email VARCHAR(100) NOT NULL,
        CONSTRAINT PK_Users PRIMARY KEY (ID)
    );
    

    IDThe , FirstName, LastNameand Emailcolumns are all set NOT NULLto ensure that values ​​in these columns cannot be null.

  • UNIQUEConstraints: Used to ensure that the values ​​in a column are unique.

    CREATE TABLE Products (
        ID INT NOT NULL,
        Name VARCHAR(100) NOT NULL,
        Description TEXT,
        SKU VARCHAR(50) UNIQUE,
        CONSTRAINT PK_Products PRIMARY KEY (ID)
    );
    

    SKUcolumn is set UNIQUEto ensure that each product has a unique SKU number.

  • PRIMARY KEYConstraint: Used to specify that one or more columns are the primary key of the table, ensuring that each row has a unique identifier.

    CREATE TABLE Orders (
        ID INT PRIMARY KEY,
        CustomerID INT NOT NULL,
        OrderDate DATETIME DEFAULT NULL,
        CONSTRAINT FK_Orders_Customers FOREIGN KEY (CustomerID) REFERENCES Customers(ID)
    );
    

    IDcolumn is set PRIMARY KEYto ensure that each order has a unique identifier.

  • FOREIGN KEYConstraints: Used to ensure that the values ​​in a column match the values ​​in a column in another table.

    CREATE TABLE OrderDetails (
        ID INT PRIMARY KEY,
        OrderID INT NOT NULL,
        ProductID INT NOT NULL,
        Quantity INT NOT NULL,
        CONSTRAINT FK_OrderDetails_Orders FOREIGN KEY (OrderID) REFERENCES Orders(ID),
        CONSTRAINT FK_OrderDetails_Products FOREIGN KEY (ProductID) REFERENCES Products(ID)
    );
    

    OrderID ProductID 列都被设置为FOREIGN KEY` to ensure that the order detail row matches the correct row in the order and product tables.

  • CHECKConstraints: Used to ensure that the values ​​in a column meet certain conditions.

    CREATE TABLE Employees (
        ID INT PRIMARY KEY,
        FirstName VARCHAR(50) NOT NULL,
        LastName VARCHAR(50) NOT NULL,
        HireDate DATE,
        Salary DECIMAL(10,2) NOT NULL,
        CONSTRAINT CK_Employees_Salary CHECK (Salary > 0)
    );
    

    Salary 列被设置为CHECK` constraint to ensure that each employee's salary is greater than 0.

By using constraints, you can protect the integrity and validity of data in SQL. When attempting to insert or update data into a table, if any constraints are violated, SQL will throw an error, preventing the transaction from committing.

3.6 Table backup and recovery

In SQL, we can use the backup and restore feature to save and restore data in the database.

The MySQL database also provides backup and recovery functions, which can mysqldumpbe backed up with the command and mysqlrestored with the command. Following is the syntax and examples for backing up and restoring MySQL database tables:

  • Backup MySQL tables

    /*备份整个数据库*/ 
    mysqldump -u root -p database_name > backup_file.sql 
    
    /*备份单个表结构和数据*/
    mysqldump -u root -p database_name table_name > backup_file.sql 
    
    /*备份单个表结构*/
    mysqldump -u root -p -d database_name table_name > backup_file.sql 
    

    When executing the backup command, -uit indicates the user name for logging in to the MySQL database, -pindicates the prompt when entering the password, database_nameindicates the name of the database to be backed up, and table_nameindicates the name of the database table to be backed up. The backup file backup_file.sqlcan be decided by oneself, and the file storage directory can also be specified at the same time.

  • restore mysql table

    /*从备份文件中还原整个数据库*/ 
    mysql -u root -p database_name < backup_file.sql 
    
    /*从备份文件中还原单个表结构和数据*/
    mysql -u root -p database_name < backup_file.sql 
    
    /*从备份文件中还原单个表结构*/
    mysql -u root -p database_name < backup_file.sql 
    

    The syntax of the restore command is roughly the same as that of the backup command, the only difference is that the backup file is used as standard input to restore the table. When performing a restore operation, care must be taken to ensure that the table names and structures in the current database table and the backup file are consistent.

It should be noted that MySQL backup and recovery commands usually require administrator privileges and take a long time to execute. At the same time, the security and management of backup files also need to be considered. In practice, backup and recovery strategies need to be carefully considered, and relevant database security and best practices adhered to.

Guess you like

Origin blog.csdn.net/fumeidonga/article/details/131144607