Home > System Tutorial > LINUX > body text

How to execute MySQL scripts in batches under Linux system?

王林
Release: 2024-03-02 12:52:38
forward
1232 people have browsed it

Linux batch execution MySQL script preface

Under Linux systems, batch execution of MySQL scripts is a common task. By executing scripts in batches, large amounts of data operations can be processed manually to improve efficiency and accuracy. This article will introduce how to execute MySQL scripts in batches under Linux systems and provide relevant code examples.

Planning to work

Before we begin, we need to ensure that the MySQL database has been installed and has permission to execute scripts. If you have not installed the MySQL Linux boot disk creation tool, you can refer to the official documentation to install it.

linux批量执行的脚本_批量执行shell脚本_linux 批量执行脚本

flow chart

The following is a flow chart for batch execution of MySQL scripts:

linux 批量执行脚本_linux批量执行的脚本_批量执行shell脚本

flowchart TD
A[开始] --> B[连接数据库]
B --> C[读取脚本文件列表]
C --> D[逐个执行脚本文件]
D --> E[执行完毕]
E --> F[关闭数据库连接]
F --> G[结束]
Copy after login

Code example to connect to database

#!/bin/bash
# 连接数据库
mysql -hlocalhost -uroot -ppassword
Copy after login

In the above codeLinux batch execution script, we use the mysql command to connect to the local MySQL database. The user name is root and the password is password. If you need to connect to a database on another host, you can replace localhost with the corresponding host name or IP address.

Read script file list

#!/bin/bash
# 读取脚本文件列表
scripts=$(ls ./scripts/*.sql)
for script in $scripts; do
echo "执行脚本文件:$script"
# 执行脚本文件的代码
done
Copy after login

In the above codeLinux batch execution script, we use the ls command to obtain all .sql files in the ./scripts/ directory and save them to the scripts variable. Then use a for loop to traverse the script files one by one and output the file name.

Execute script file

#!/bin/bash
# 执行脚本文件
scripts=$(ls ./scripts/*.sql)
for script in $scripts; do
echo "执行脚本文件:$script"
mysql -hlocalhost -uroot -ppassword < $script
done
Copy after login

In the above code, in each loop, we use the mysql command to execute the script file.

The above is the detailed content of How to execute MySQL scripts in batches under Linux system?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:itcool.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template