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.
flow chart
The following is a flow chart for batch execution of MySQL scripts:
flowchart TD A[开始] --> B[连接数据库] B --> C[读取脚本文件列表] C --> D[逐个执行脚本文件] D --> E[执行完毕] E --> F[关闭数据库连接] F --> G[结束]
Code example to connect to database
#!/bin/bash # 连接数据库 mysql -hlocalhost -uroot -ppassword
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
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
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!