shell 循环执行sql脚本

 

线上批量更新,数量过多,流程上必须写脚本,就试着先写个简单的,逻辑: 每次更新一条,根据id逐条更新。

后续其实可以优化为分页批量执行(limit x,y  或者 where id < last and id >= id +1000),效率会更高。

#!/bin/bash

i=1
step=1
#cnt=$(/usr/local/MySQL/bin/mysql -u root -p -Dtf_test -s -e "${cmd}")
while (($i<=3))
do
  #${cnt}
  cmd="update test_1 set no=11 where id=$i"
  echo ${cmd}
  /usr/local/MySQL/bin/mysql -h'localhost' -u'root' -p'root'  -D tf_test -s -e "${cmd}"
  i=`expr $i + $step`
done
echo "执行完毕:${i}"

sql  命令行的说明:

-h, --host=name     Connect to host.  连接的host 
-u, --user=name     User for login if not current user. 指定的用户名
-p, --password[=name] 指定的密码
-P, --port=#        Port number to use for connection.  指定的数据端口号
-D, --database=name Database to use.  指定数据库的 database
-e, --execute=name  Execute command and quit. (Disables --force and history 执行具体的sql
-s, --silent        Be more silent. Print results with a tab as separator, 以制表符作为分隔符打印结果

需要注意一点的是,环境中 直接执行  mysql  -uroot -proot 是没有问题的,在shell 脚本中,  -proot  要写成 -p'root',否则会被认为 root 是 database,执行错误

mysql的命令:

Usage: /usr/local/MySQL/bin/mysql [OPTIONS] [database]
  -?, --help          Display this help and exit.
  -I, --help          Synonym for -?
  --auto-rehash       Enable automatic rehashing. One doesn't need to use
                      'rehash' to get table and field completion, but startup
                      and reconnecting may take a longer time. Disable with
                      --disable-auto-rehash.
                      (Defaults to on; use --skip-auto-rehash to disable.)
  -A, --no-auto-rehash
                      No automatic rehashing. One has to use 'rehash' to get
                      table and field completion. This gives a quicker start of
                      mysql and disables rehashing on reconnect.
  --auto-vertical-output
                      Automatically switch to vertical output mode if the
                      result is wider than the terminal width.
  -B, --batch         Don't use history file. Disable interactive behavior.
                      (Enables --silent.)
  --bind-address=name IP address to bind to.
  --binary-as-hex     Print binary data as hex
  --character-sets-dir=name
                      Directory for character set files.
  --column-type-info  Display column type information.
  -c, --comments      Preserve comments. Send comments to the server. The
                      default is --skip-comments (discard comments), enable
                      with --comments.
  -C, --compress      Use compression in server/client protocol.
  -#, --debug[=#]     This is a non-debug version. Catch this and exit.
  --debug-check       This is a non-debug version. Catch this and exit.
  -T, --debug-info    This is a non-debug version. Catch this and exit.
  -D, --database=name Database to use.
  --default-character-set=name
                      Set the default character set.
  --delimiter=name    Delimiter to be used.
  --enable-cleartext-plugin
                      Enable/disable the clear text authentication plugin.
  -e, --execute=name  Execute command and quit. (Disables --force and history
                      file.)
  -E, --vertical      Print the output of a query (rows) vertically.
  -f, --force         Continue even if we get an SQL error.
  --histignore=name   A colon-separated list of patterns to keep statements
                      from getting logged into syslog and mysql history.
  -G, --named-commands
                      Enable named commands. Named commands mean this program's
                      internal commands; see mysql> help . When enabled, the
                      named commands can be used from any line of the query,
                      otherwise only from the first line, before an enter.
                      Disable with --disable-named-commands. This option is
                      disabled by default.
  -i, --ignore-spaces Ignore space after function names.
  --init-command=name SQL Command to execute when connecting to MySQL server.
                      Will automatically be re-executed when reconnecting.
  --local-infile      Enable/disable LOAD DATA LOCAL INFILE.
  -b, --no-beep       Turn off beep on error.
  -h, --host=name     Connect to host.
  -H, --html          Produce HTML output.
  -X, --xml           Produce XML output.
  --line-numbers      Write line numbers for errors.
                      (Defaults to on; use --skip-line-numbers to disable.)
  -L, --skip-line-numbers
                      Don't write line number for errors.
  -n, --unbuffered    Flush buffer after each query.
  --column-names      Write column names in results.
                      (Defaults to on; use --skip-column-names to disable.)
  -N, --skip-column-names
                      Don't write column names in results.
  --sigint-ignore     Ignore SIGINT (CTRL-C).
  -o, --one-database  Ignore statements except those that occur while the
                      default database is the one named at the command line.
  --pager[=name]      Pager to use to display results. If you don't supply an
                      option, the default pager is taken from your ENV variable
                      PAGER. Valid pagers are less, more, cat [> filename],
                      etc. See interactive help (\h) also. This option does not
                      work in batch mode. Disable with --disable-pager. This
                      option is disabled by default.
  -p, --password[=name]
                      Password to use when connecting to server. If password is
                      not given it's asked from the tty.
  -P, --port=#        Port number to use for connection or 0 for default to, in
                      order of preference, my.cnf, $MYSQL_TCP_PORT,
                      /etc/services, built-in default (3306).
  --prompt=name       Set the mysql prompt to this value.
  --protocol=name     The protocol to use for connection (tcp, socket, pipe,
                      memory).
  -q, --quick         Don't cache result, print it row by row. This may slow
                      down the server if the output is suspended. Doesn't use
                      history file.
  -r, --raw           Write fields without conversion. Used with --batch.
  --reconnect         Reconnect if the connection is lost. Disable with
                      --disable-reconnect. This option is enabled by default.
                      (Defaults to on; use --skip-reconnect to disable.)
  -s, --silent        Be more silent. Print results with a tab as separator,
                      each row on new line.
  -S, --socket=name   The socket file to use for connection.
  --server-public-key-path=name
                      File path to the server public RSA key in PEM format.
  --get-server-public-key
                      Get server public key
  --ssl-mode=name     SSL connection mode.
  --ssl-ca=name       CA file in PEM format.
  --ssl-capath=name   CA directory.
  --ssl-cert=name     X509 cert in PEM format.
  --ssl-cipher=name   SSL cipher to use.
  --ssl-key=name      X509 key in PEM format.
  --ssl-crl=name      Certificate revocation list.
  --ssl-crlpath=name  Certificate revocation list path.
  --tls-version=name  TLS version to use, permitted values are: TLSv1, TLSv1.1,
                      TLSv1.2
  --ssl-fips-mode=name
                      SSL FIPS mode (applies only for OpenSSL); permitted
                      values are: OFF, ON, STRICT
  -t, --table         Output in table format.
  --tee=name          Append everything into outfile. See interactive help (\h)
                      also. Does not work in batch mode. Disable with
                      --disable-tee. This option is disabled by default.
  -u, --user=name     User for login if not current user.
  -U, --safe-updates  Only allow UPDATE and DELETE that uses keys.
  -U, --i-am-a-dummy  Synonym for option --safe-updates, -U.
  -v, --verbose       Write more. (-v -v -v gives the table output format).
  -V, --version       Output version information and exit.
  -w, --wait          Wait and retry if connection is down.
  --connect-timeout=# Number of seconds before connection timeout.
  --max-allowed-packet=#
                      The maximum packet length to send to or receive from
                      server.
  --net-buffer-length=#
                      The buffer size for TCP/IP and socket communication.
  --select-limit=#    Automatic limit for SELECT when using --safe-updates.
  --max-join-size=#   Automatic limit for rows in a join when using
                      --safe-updates.
  --show-warnings     Show warnings after every statement.
  -j, --syslog        Log filtered interactive commands to syslog. Filtering of
                      commands depends on the patterns supplied via histignore
                      option besides the default patterns.
  --plugin-dir=name   Directory for client-side plugins.
  --default-auth=name Default authentication client-side plugin to use.
  --binary-mode       By default, ASCII '\0' is disallowed and '\r\n' is
                      translated to '\n'. This switch turns off both features,
                      and also turns off parsing of all clientcommands except
                      \C and DELIMITER, in non-interactive mode (for input
                      piped to mysql or loaded using the 'source' command).
                      This is necessary when processing output from mysqlbinlog
                      that may contain blobs.
  --connect-expired-password
                      Notify the server that this client is prepared to handle
                      expired password sandbox mode.

Default options are read from the following files in the given order:
/etc/my.cnf /etc/mysql/my.cnf /usr/local/mysql/etc/my.cnf ~/.my.cnf
The following groups are read: mysql client
The following options may be given as the first argument:
--print-defaults        Print the program argument list and exit.
--no-defaults           Don't read default options from any option file,
                        except for login file.
--defaults-file=#       Only read default options from the given file #.
--defaults-extra-file=# Read this file after the global files are read.
--defaults-group-suffix=#
                        Also read groups with concat(group, suffix)
--login-path=#          Read this path from the login file.

Variables (--variable-name=value)

 

 

 

 

 

 

### 回答1: shell脚本可以通过调用mysql命令来执行SQL语句。例如,可以使用以下命令执行SQL语句mysql -h主机名 -u用户名 -p密码 数据库名 -e "SQL语句" 其中,主机名是数据库所在的主机名,用户名和密码是数据库的登录凭据,数据库名是要执行SQL语句的数据库名称,SQL语句是要执行SQL语句。 例如,以下是一个简单的shell脚本,用于执行SQL语句并将结果输出到文件中: #!/bin/bash mysql -hlocalhost -uroot -p123456 testdb -e "SELECT * FROM users" > output.txt 该脚本将连接到名为testdb的数据库,并执行SELECT * FROM users语句,将结果输出到output.txt文件中。 ### 回答2: Shell脚本是一种用于Unix和Linux系统的脚本语言,可以用于管理文件系统、执行命令等。在Shell脚本中,我们可以使用各种命令和工具来完成一些常见的任务,其中SQL是一个常见的用途之一。 执行SQL语句需要一个数据库管理系统(DBMS),比如MySQL和Oracle等。一般来说,我们需要首先在Shell脚本中安装适合的DBMS并建立连接。连接数据库后,我们可以使用Shell脚本执行SQL语句并获取返回值。 我们可以使用以下命令在Shell脚本执行SQL: 1. mysql命令 这是一个常见的用于管理MySQL数据库的命令,可以直接在Shell执行SQL语句。我们可以使用以下命令来运行我们的SQL语句mysql -u user -p password -h hostname -P port -D dbname -e "SQL statement" 其中,-u指定用户名,-p指定密码,-h指定主机名,-P指定端口号,-D指定数据库名,-e指定要执行SQL语句。 2. psql命令 这是一个用于管理PostgreSQL数据库的命令,也可以在Shell执行SQL。类似于mysql命令,我们可以使用以下命令来运行我们的SQL语句: psql -h hostname -p port -U username -d dbname -c "SQL statement" 其中,-h指定主机名,-p指定端口号,-U指定用户名,-d指定数据库名,-c指定要执行SQL语句。 有些时候,我们需要在Shell脚本执行多条SQL语句或者使用循环来动态执行SQL,这就需要对Shell脚本的编程能力有一定的要求了。但无论在哪种情况下,我们都需要了解DBMS和Shell脚本的基本语法才能编写出安全高效的代码。 ### 回答3: Shell脚本是一种在Unix或Linux操作系统中使用的编程语言,其脚本文件使用Shell解释器来执行执行SQL语句通常是在数据库中操作数据,与shell脚本紧密相关,尤其是在自动化任务方面。 在Shell脚本执行SQL语句的过程: 1. 指定数据库连接信息:需要在Shell脚本中指定数据库连接信息,包括数据库服务器IP地址、数据库端口、登录名和密码等。可以将这些信息定义为变量,然后在脚本中使用这些变量,方便修改和维护。 2. 编写SQL语句:在Shell脚本中编写需要在数据库中执行SQL语句。这些SQL语句可以是查询、插入、更新或删除等操作。注意在写SQL语句时候要通过变量的方式传值,防止SQL注入。 3. 执行SQL语句:通过shell执行数据库客户端程序例如 mysql,postgresql,oracle等,同时传递执行SQL语句。 4. 处理结果:执行SQL语句后,可以获取数据库执行结果,包括数据库操作受影响的行数、查询结果等。可以通过Shell脚本来处理这些结果,比如进行统计、分析、输出等操作。 在实际应用中,Shell脚本执行SQL通常被用于批量处理数据、自动化任务或数据备份等场景,如某个时期对数据进行统计,定时清洗过期数据或导出数据报表。通过Shell脚本执行SQL语句可以极大提高效率,降低手动操作过程中出错可能,保证数据一致性和可靠性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值