Linux shell脚本批量执行sql脚本(Linux执行sql脚本)

如果要使用Shell脚本批量执行SQL脚本,首先确保已安装数据库命令行工具(如mysql、psql等)。

以下示例将使用MySQL数据库进行演示。

如果你使用的是其他数据库,如PostgreSQL,要对一下脚本进行修改。

图片[1]-Linux shell脚本批量执行sql脚本(Linux执行sql脚本)-不念博客

创建一个包含SQL文件名的文本文件,例如sql_files.txt:

script1.sql
script2.sql
script3.sql

编写Shell脚本(例如:execute_sql_scripts.sh):

#!/bin/bash

# 指定数据库连接信息
db_host="localhost"
db_port="3306"
db_user="your_username"
db_password="your_password"
db_name="your_database"

# 指定SQL文件列表
sql_files_list="sql_files.txt"

# 读取SQL文件列表并执行
while read -r sql_file; do
  # 检查文件是否存在
  if [ -f "$sql_file" ]; then
    echo "正在执行 $sql_file ..."

    # 执行SQL文件
    mysql -h "$db_host" -P "$db_port" -u "$db_user" -p"$db_password" "$db_name" < "$sql_file"

    # 检查执行结果
    if [ $? -eq 0 ]; then
      echo "成功执行 $sql_file"
    else
      echo "执行 $sql_file 时发生错误"
    fi
  else
    echo "文件 $sql_file 不存在,跳过执行。"
  fi
done <"$sql_files_list"

赋予脚本执行权限:

chmod +x execute_sql_scripts.sh

运行脚本:

./execute_sql_scripts.sh

这将根据sql_files.txt文件中的SQL文件名批量执行SQL脚本。

你要确保用正确的数据库连接信息替换示例脚本中的占位符。

© 版权声明
THE END
喜欢就支持一下吧
点赞107赞赏 分享
评论 抢沙发
头像
欢迎光临不念博客,留下您的想法和建议,祝您有愉快的一天~
提交
头像

昵称

取消
昵称代码图片

    暂无评论内容