数据库大王mysql---linux

数据库大王mysql---linux

一,什么是数据库

关系型数据库

高级excel

非关系型数据库

键值对

二,安装数据库并进行安全初始化

搜索mysql 服务包

shell 复制代码
[root@mysql ~]# dnf search mysql
Updating Subscription Management repositories.
Unable to read consumer identity

This system is not registered with an entitlement server. You can use "rhc" or "subscription-manager" to register.

=================================== Name & Summary Matched: mysql ====================================
mysql.x86_64 : MySQL client programs and shared libraries
apr-util-mysql.x86_64 : APR utility library MySQL DBD driver
dovecot-mysql.x86_64 : MySQL back end for dovecot
mysql-common.x86_64 : The shared files required for MySQL server and client
mysql-errmsg.x86_64 : The error messages files required by MySQL server
mysql-selinux.noarch : SELinux policy modules for MySQL and MariaDB packages
mysql-server.x86_64 : The MySQL server and related files
pcp-pmda-mysql.x86_64 : Performance Co-Pilot (PCP) metrics for MySQL
perl-DBD-MySQL.x86_64 : A MySQL interface for Perl
php-mysqlnd.x86_64 : A module for PHP applications that use MySQL databases
postfix-mysql.x86_64 : Postfix MySQL map support
python3-PyMySQL.noarch : Pure-Python MySQL client library
python3.11-PyMySQL.noarch : Pure-Python MySQL client library
python3.11-PyMySQL+rsa.noarch : Metapackage for python3.11-PyMySQL: rsa extras
python3.12-PyMySQL.noarch : Pure-Python MySQL client library
python3.12-PyMySQL+rsa.noarch : Metapackage for python3.12-PyMySQL: rsa extras
qt5-qtbase-mysql.i686 : MySQL driver for Qt5's SQL classes
qt5-qtbase-mysql.x86_64 : MySQL driver for Qt5's SQL classes
rsyslog-mysql.x86_64 : MySQL support for rsyslog
rubygem-mysql2.x86_64 : A simple, fast Mysql library for Ruby, binding to libmysql
======================================= Summary Matched: mysql =======================================
mariadb-java-client.noarch : Connects applications developed in Java to MariaDB and MySQL databases
mariadb-server-utils.x86_64 : Non-essential server utilities for MariaDB/MySQL applications
perl-DBD-MariaDB.x86_64 : MariaDB and MySQL driver for the Perl5 Database Interface (DBI)

安装MySQL服务

shell 复制代码
[root@mysql ~]# dnf install mysql-server.x86_64  -y
Updating Subscription Management repositories.
Unable to read consumer identity

This system is not registered with an entitlement server. You can use "rhc" or "subscription-manager" to register.

AppStream                                                             3.1 MB/s | 3.2 kB     00:00
BaseOS                                                                2.7 MB/s | 2.7 kB     00:00
Dependencies resolved.
======================================================================================================
 Package                            Architecture   Version                    Repository         Size
======================================================================================================
Installing:
 mysql-server                       x86_64         8.0.36-1.el9_3             AppStream          17 M
Installing dependencies:

验证MySQL服务是否存在并开启服务

shell 复制代码
[root@mysql ~]# systemctl status mysqld.service     #查看服务状态
○ mysqld.service - MySQL 8.0 database server
     Loaded: loaded (/usr/lib/systemd/system/mysqld.service; disabled; preset: disabled)
     Active: inactive (dead)
[root@mysql ~]# systemctl start mysqld.service     #开启服务
[root@mysql ~]# systemctl status mysqld.service
● mysqld.service - MySQL 8.0 database server
     Loaded: loaded (/usr/lib/systemd/system/mysqld.service; disabled; preset: disabled)
     Active: active (running) since Tue 2026-01-13 21:14:35 CST; 6s ago
    Process: 30532 ExecStartPre=/usr/libexec/mysql-check-socket (code=exited, status=0/SUCCESS)
    Process: 30554 ExecStartPre=/usr/libexec/mysql-prepare-db-dir mysqld.service (code=exited, status>
   Main PID: 30628 (mysqld)
     Status: "Server is operational"
      Tasks: 38 (limit: 22944)
     Memory: 467.6M
        CPU: 3.861s
     CGroup: /system.slice/mysqld.service
             └─30628 /usr/libexec/mysqld --basedir=/usr

Jan 13 21:14:30 mysql systemd[1]: Starting MySQL 8.0 database server...
Jan 13 21:14:30 mysql mysql-prepare-db-dir[30554]: Initializing MySQL database
Jan 13 21:14:35 mysql systemd[1]: Started MySQL 8.0 database server.

[root@mysql ~]# systemctl enable --now mysqld.service    #开机自启
Created symlink /etc/systemd/system/multi-user.target.wants/mysqld.service → /usr/lib/systemd/system/mysqld.service.
[root@mysql ~]# mysql
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 8
Server version: 8.0.36 Source distribution

数据库安全初始化

shell 复制代码
[root@mysql ~]# mysql_secure_installation       #安全初始化命令

Securing the MySQL server deployment.

Connecting to MySQL using a blank password.

VALIDATE PASSWORD COMPONENT can be used to test passwords
and improve security. It checks the strength of password
and allows the users to set only those passwords which are
secure enough. Would you like to setup VALIDATE PASSWORD component?

Press y|Y for Yes, any other key for No: y             #是否更改密码

There are three levels of password validation policy:           #更改密码安全等级

LOW    Length >= 8
MEDIUM Length >= 8, numeric, mixed case, and special characters
STRONG Length >= 8, numeric, mixed case, special characters and dictionary                  file

Please enter 0 = LOW, 1 = MEDIUM and 2 = STRONG: 0
Please set the password for root here.

New password:                            #新密码

Re-enter new password:                   #验证新密码

Estimated strength of the password: 50
Do you wish to continue with the password provided?(Press y|Y for Yes, any other key for No) : y     #是否使用该密码
By default, a MySQL installation has an anonymous user,
allowing anyone to log into MySQL without having to have
a user account created for them. This is intended only for
testing, and to make the installation go a bit smoother.
You should remove them before moving into a production
environment.

Remove anonymous users? (Press y|Y for Yes, any other key for No) : y       #是否去除匿名用户登录
Success.


Normally, root should only be allowed to connect from
'localhost'. This ensures that someone cannot guess at
the root password from the network.

Disallow root login remotely? (Press y|Y for Yes, any other key for No) : y     #是否拒绝超级用户远程登录
Success.

By default, MySQL comes with a database named 'test' that
anyone can access. This is also intended only for testing,
and should be removed before moving into a production
environment.


Remove test database and access to it? (Press y|Y for Yes, any other key for No) : y    #是否测试库
 - Dropping test database...
Success.

 - Removing privileges on test database...
Success.

Reloading the privilege tables will ensure that all changes
made so far will take effect immediately.

Reload privilege tables now? (Press y|Y for Yes, any other key for No) : y            #是否刷新数据库
Success.

All done!

测试安装成功与否

复制代码
[root@mysql ~]# mysql -u root -p
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 13
Server version: 8.0.36 Source distribution

Copyright (c) 2000, 2024, Oracle and/or its affiliates.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql>

数据库的基础操作(sql语句的基本知识)

shell 复制代码
#显示库名称
mysql> SHOW DATABASES;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
4 rows in set (0.00 sec)

#创建数据库
mysql> CREATE DATABASES lsy;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DATABASES lsy' at line 1
mysql> CREATE DATABASE lsy;
Query OK, 1 row affected (0.01 sec)

mysql> SHOW DATABASES;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| lsy                |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
5 rows in set (0.00 sec)

#使用数据库
mysql> USE lsy;
Database changed

#显示库中的表
mysql> USE lsy;
Database changed
mysql> SHOW TABLES;
Empty set (0.00 sec)

#显示其他库中的表
#以MySQL为例子
mysql> SHOW TABLES FROM mysql;
+------------------------------------------------------+
| Tables_in_mysql                                      |
+------------------------------------------------------+
| columns_priv                                         |
| component                                            |
| db                                                   |
| default_roles                                        |
| engine_cost                                          |
| func                                                 |
| general_log                                          |
| global_grants                                        |
| gtid_executed                                        |
| help_category                                        |
| help_keyword                                         |
| help_relation                                        |
| help_topic                                           |
| innodb_index_stats                                   |
| innodb_table_stats                                   |
| password_history                                     |
| plugin                                               |
| procs_priv                                           |
| proxies_priv                                         |
| replication_asynchronous_connection_failover         |
| replication_asynchronous_connection_failover_managed |
| replication_group_configuration_version              |
| replication_group_member_actions                     |
| role_edges                                           |
| server_cost                                          |
| servers                                              |
| slave_master_info                                    |
| slave_relay_log_info                                 |
| slave_worker_info                                    |
| slow_log                                             |
| tables_priv                                          |
| time_zone                                            |
| time_zone_leap_second                                |
| time_zone_name                                       |
| time_zone_transition                                 |
| time_zone_transition_type                            |
| user                                                 |
+------------------------------------------------------+
37 rows in set (0.00 sec)

#在MySQL中建立表
mysql> CREATE TABLE mysql.userlist;
mysql> CREATE TABLE mysql.userlist ( username varchar(10)  null , passwd varchar(50) not null ); 
#括号内依次为表头名称 字符长度 not null为非空
Query OK, 0 rows affected (0.01 sec)

mysql> SHOW TABLES FROM mysql;
+------------------------------------------------------+
| Tables_in_mysql                                      |
+------------------------------------------------------+
| columns_priv                                         |
| component                                            |
| db                                                   |
| default_roles                                        |
| engine_cost                                          |
| func                                                 |
| general_log                                          |
| global_grants                                        |
| gtid_executed                                        |
| help_category                                        |
| help_keyword                                         |
| help_relation                                        |
| help_topic                                           |
| innodb_index_stats                                   |
| innodb_table_stats                                   |
| password_history                                     |
| plugin                                               |
| procs_priv                                           |
| proxies_priv                                         |
| replication_asynchronous_connection_failover         |
| replication_asynchronous_connection_failover_managed |
| replication_group_configuration_version              |
| replication_group_member_actions                     |
| role_edges                                           |
| server_cost                                          |
| servers                                              |
| slave_master_info                                    |
| slave_relay_log_info                                 |
| slave_worker_info                                    |
| slow_log                                             |
| tables_priv                                          |
| time_zone                                            |
| time_zone_leap_second                                |
| time_zone_name                                       |
| time_zone_transition                                 |
| time_zone_transition_type                            |
| user                                                 |
| userlist                                             |
+------------------------------------------------------+
38 rows in set (0.00 sec)

#删除数据库
mysql> DROP TABLE mysql.userlist ;
Query OK, 0 rows affected (0.01 sec)

mysql> SHOW TABLES FROM mysql;
+------------------------------------------------------+
| Tables_in_mysql                                      |
+------------------------------------------------------+
| columns_priv                                         |
| component                                            |
| db                                                   |
| default_roles                                        |
| engine_cost                                          |
| func                                                 |
| general_log                                          |
| global_grants                                        |
| gtid_executed                                        |
| help_category                                        |
| help_keyword                                         |
| help_relation                                        |
| help_topic                                           |
| innodb_index_stats                                   |
| innodb_table_stats                                   |
| password_history                                     |
| plugin                                               |
| procs_priv                                           |
| proxies_priv                                         |
| replication_asynchronous_connection_failover         |
| replication_asynchronous_connection_failover_managed |
| replication_group_configuration_version              |
| replication_group_member_actions                     |
| role_edges                                           |
| server_cost                                          |
| servers                                              |
| slave_master_info                                    |
| slave_relay_log_info                                 |
| slave_worker_info                                    |
| slow_log                                             |
| tables_priv                                          |
| time_zone                                            |
| time_zone_leap_second                                |
| time_zone_name                                       |
| time_zone_transition                                 |
| time_zone_transition_type                            |
| user                                                 |
+------------------------------------------------------+
37 rows in set (0.00 sec)


#建立当前库内表
mysql> CREATE TABLE userlist ( username varchar(10)  null , passwd varchar(50) not null );
Query OK, 0 rows affected (0.02 sec)

mysql> SHOW TABLES;
+---------------+
| Tables_in_lsy |
+---------------+
| userlist      |
+---------------+
1 row in set (0.00 sec)

#插入信息
mysql> INSERT INTO userlist VALUES ('user1','123');
Query OK, 1 row affected (0.00 sec)


#插入多条数据
mysql> INSERT INTO userlist VALUES ('user3','333'),('user2','222');
Query OK, 2 rows affected (0.00 sec)
Records: 2  Duplicates: 0  Warnings: 0

#查看所有数据
mysql> SELECT * FROM userlist;
+----------+--------+
| username | passwd |
+----------+--------+
| user1    | 123    |
+----------+--------+
1 row in set (0.00 sec)

#查询某列

mysql> SELECT  username from userlist ;
+----------+
| username |
+----------+
| user1    |
| user3    |
| user2    |
+----------+
3 rows in set (0.00 sec)

#查询某列中某个固定的值多列可加and后面加条件
mysql> SELECT  username from userlist WHERE passwd='333' ;
+----------+
| username |
+----------+
| user3    |
+----------+
1 row in set (0.01 sec)

#修改数据库名称
[root@mysql mysql]# cd /var/lib/mysql
[root@mysql mysql]# mv  lsy/ lvsi

#!!!不建议修改数据库名称,会导致数据丢失!!!#

#修改表名称
mysql> SHOW TABLES;
+---------------+
| Tables_in_lsy |
+---------------+
| userlist      |
+---------------+
1 row in set (0.00 sec)

mysql> ALTER TABLE userlist RENAME user_list;
Query OK, 0 rows affected (0.01 sec)

mysql> SHOW TABLES;
+---------------+
| Tables_in_lsy |
+---------------+
| user_list     |
+---------------+
1 row in set (0.00 sec)

#增加一列
mysql> DESC user_list;
+----------+-------------+------+-----+---------+-------+
| Field    | Type        | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+-------+
| username | varchar(10) | YES  |     | NULL    |       |
| passwd   | varchar(50) | NO   |     | NULL    |       |
+----------+-------------+------+-----+---------+-------+
2 rows in set (0.01 sec)

mysql> ALTER TABLE user_list ADD age varchar(4) ;
Query OK, 0 rows affected (0.02 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> DESC user_list;
+----------+-------------+------+-----+---------+-------+
| Field    | Type        | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+-------+
| username | varchar(10) | YES  |     | NULL    |       |
| passwd   | varchar(50) | NO   |     | NULL    |       |
| age      | varchar(4)  | YES  |     | NULL    |       |
+----------+-------------+------+-----+---------+-------+
3 rows in set (0.00 sec)

#删除列
mysql> ALTER TABLE user_list DROP age  ;
Query OK, 0 rows affected (0.01 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> DESC user_list;
+----------+-------------+------+-----+---------+-------+
| Field    | Type        | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+-------+
| username | varchar(10) | YES  |     | NULL    |       |
| passwd   | varchar(50) | NO   |     | NULL    |       |
+----------+-------------+------+-----+---------+-------+
2 rows in set (0.00 sec)

#插入列到passwd前
mysql> ALTER TABLE user_list ADD age varchar(4) AFTER username;
Query OK, 0 rows affected (0.01 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> DESC user_list;
+----------+-------------+------+-----+---------+-------+
| Field    | Type        | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+-------+
| username | varchar(10) | YES  |     | NULL    |       |
| age      | varchar(4)  | YES  |     | NULL    |       |
| passwd   | varchar(50) | NO   |     | NULL    |       |
+----------+-------------+------+-----+---------+-------+
3 rows in set (0.01 sec)

#更新某列数据
mysql> SELECT * FROM user_list;
+----------+------+--------+
| username | age  | passwd |
+----------+------+--------+
| user1    | NULL | 123    |
| user3    | NULL | 333    |
| user2    | NULL | 222    |
+----------+------+--------+
3 rows in set (0.00 sec)

mysql> UPDATE user_list SET age='20';
Query OK, 3 rows affected (0.00 sec)
Rows matched: 3  Changed: 3  Warnings: 0

mysql> SELECT * FROM user_list;
+----------+------+--------+
| username | age  | passwd |
+----------+------+--------+
| user1    | 20   | 123    |
| user3    | 20   | 333    |
| user2    | 20   | 222    |
+----------+------+--------+
3 rows in set (0.00 sec)

#更新指定数据
mysql> UPDATE user_list SET age='15' WHERE username='user3';
Query OK, 1 row affected (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql> SELECT * FROM user_list;
+----------+------+--------+
| username | age  | passwd |
+----------+------+--------+
| user1    | 20   | 123    |
| user3    | 15   | 333    |
| user2    | 20   | 222    |
+----------+------+--------+
3 rows in set (0.00 sec)

#备份数据库中所有数据到all.sql文件中
[root@mysql mysql]# mysqldump -uroot -p12345678 -A > /mnt/all.sql
mysqldump: [Warning] Using a password on the command line interface can be insecure.
-- MySQL dump 10.13  Distrib 8.0.36, for Linux (x86_64)
[root@mysql mysql]# mysqldump -uroot -p12345678 -A |wc -l
mysqldump: [Warning] Using a password on the command line interface can be insecure.
1071


#备份数据库但不备份数据
[root@mysql mysql]# mysqldump -uroot -p12345678 -A --no-data > /mnt/all.sql
[root@mysql mysql]# mysqldump -uroot -p12345678 -A --no-data |wc -l
mysqldump: [Warning] Using a password on the command line interface can be insecure.
760

#备份指定的库
[root@mysql mysql]# mysqldump -uroot -p12345678 lsy > /mnt/lsy.sql

#删除表
mysql> DROP TABLE user_list;
Query OK, 0 rows affected (0.00 sec)

mysql> SELECT * FROM user_list;
ERROR 1146 (42S02): Table 'lsy.user_list' doesn't exist
mysql>

#删除库
mysql> DROP DATABASE lsy;
Query OK, 0 rows affected (0.01 sec)

mysql> SHOW DATABASES ;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
4 rows in set (0.01 sec)



#恢复数据库
[root@mysql mysql]# mysql -uroot -p12345678  -e "SHOW DATABASES"
mysql: [Warning] Using a password on the command line interface can be insecure.
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
[root@mysql mysql]# mysql -uroot -p12345678 < /mnt/lsy.sql
mysql: [Warning] Using a password on the command line interface can be insecure.
ERROR 1046 (3D000) at line 22: No database selected

#创建表
[root@mysql mysql]# mysql -uroot -p12345678 -e "CREATE DATABASE lsy"
mysql: [Warning] Using a password on the command line interface can be insecure.
[root@mysql mysql]# mysql -uroot -p12345678  -e "SHOW DATABASES"
mysql: [Warning] Using a password on the command line interface can be insecure.
+--------------------+
| Database           |
+--------------------+
| information_schema |
| lsy                |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
#恢复备份
[root@mysql mysql]# mysql -uroot -p12345678 lsy < /mnt/lsy.sql
mysql: [Warning] Using a password on the command line interface can be insecure.
[root@mysql mysql]# mysql -uroot -p12345678  -e "SHOW DATABASES"
mysql: [Warning] Using a password on the command line interface can be insecure.
+--------------------+
| Database           |
+--------------------+
| information_schema |
| lsy                |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
#!!!注意本文在实验环境中进行为高效实验故裸露数据库密码,生产环境中不可裸露密码!!!#
#应该使用
[root@mysql mysql]# mysql -uroot -p ......
相关推荐
DFT计算杂谈12 小时前
vasp如何计算金属的铁电极化强度?
数据库
EterNity_TiMe_12 小时前
别让告警变成噪音:用Prometheus和Alertmanager搭一套可远程查看的监控系统
数据库·人工智能·ai·postgresql·prometheus·cpolar
jieyucx12 小时前
【系统安全铁律】解密 Linux 权限三色数字密码:chmod 最小化赋权与生产环境避坑指南
linux·安全·系统安全·权限·chmod·777
不超限12 小时前
Postgresql 数据库 自增字段,Vastbase 无效的问题
数据库
阿坤带你走近大数据13 小时前
Oracle新老SQL写法对比
数据库·sql·oracle
还是鼠鼠13 小时前
AI掘金头条新闻系统 (Toutiao News)-缓存相关推荐新闻
后端·python·mysql·fastapi·web
AOwhisky13 小时前
Linux(CentOS)系统管理入门笔记(第四期)——文件系统(下篇):文件与目录操作实战——cpmvmkdirrmln
linux·运维·笔记·centos·云计算·文件系统
努力努力再努力wz13 小时前
【高性能网络库与HTTP Server系列】:基于主从 Reactor 模型实现高性能 C++ 网络库与 HTTP Server
开发语言·网络·数据结构·数据库·c++·网络协议·http
岑梓铭14 小时前
考研408《操作系统》复习笔记,第四章《4.2.2 文件操作、文件共享、文件保护》
linux·考研·操作系统·文件系统·408
HackTwoHub14 小时前
某单位 CMS 完整渗透链、SQL 注入→后台拿权→绕过宝塔 Waf 上线 shell
数据库·人工智能·sql·安全·网络安全·系统安全·安全架构