命令行中執行批量SQL的方法


基礎信息介紹

  測試庫:test;

  測試表:user;

  user表定義:

CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` char(30) NOT NULL,
  `age` int(11) NOT NULL,
  `gender` tinyint(1) DEFAULT '1' COMMENT '性別:1男;2女',
  `addr` char(30) NOT NULL,
  `status` tinyint(1) DEFAULT '1',
  PRIMARY KEY (`id`),
  KEY `idx` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4

  希望一次性執行的命令如下:

# 指定數據庫
use test;

# 清空user表
truncate table user;

# 插入若干條數據
insert into user
    (id, name, age, gender, addr, status)
values
    (1, 'a', 1, 1, 'beijing', 1),
    (2, 'a', 1, 1, 'beijing', 1),
    (3, 'a', 1, 1, 'beijing', 1),
    (4, 'a', 1, 1, 'beijing', 1),
    (5, 'a', 1, 1, 'beijing', 1);

# 刪除一條數據
delete from user where id=4;

# 修改一條數據
update user set status=0 where id=5;

# 查看所有記錄
select * from user;

  接下來就用下面列舉的3種方式,在命令行中一次性執行上面的sql。  

 

方式1:登錄mysql后source

  將要執行的sql保存到一個文件中,我這里將其命名為command.sql,命名隨意,后綴.sql是為了便於識別是sql代碼,也可以執行其他的比如.txt或者.cmd,與此同時我將command.sql保存到/tmp目錄下。

  登錄進入mysql,然后使用source命令,參數就是保存sql的文件絕對路徑,sql文件的保存路徑沒有特殊要求,只要通過路徑找到文件即可;

  下面是示例:

# 登錄到mysql
$ mysql -uroot -p
Enter password:
......

# 使用source命令,指定sql文件所在的絕對路徑
mysql> source /tmp/command.sql
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
Query OK, 0 rows affected (0.00 sec)

Query OK, 5 rows affected (0.00 sec)
Records: 5  Duplicates: 0  Warnings: 0

Query OK, 1 row affected (0.00 sec)

Query OK, 1 row affected (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 0

+----+------+-----+--------+---------+--------+
| id | name | age | gender | addr    | status |
+----+------+-----+--------+---------+--------+
|  1 | a    |   1 |      1 | beijing |      1 |
|  2 | a    |   1 |      1 | beijing |      1 |
|  3 | a    |   1 |      1 | beijing |      1 |
|  5 | a    |   1 |      1 | beijing |      0 |
+----+------+-----+--------+---------+--------+
4 rows in set (0.00 sec)

mysql>

 

方式2:mysql -u -p < command.sql

  先將要執行的sql保存到文件中,此處仍為/tmp/command.sql;

$ mysql -uroot -p < /tmp/command.sql
Enter password:
id	name	age	gender	addr	status
1	a	1	1	beijing	1
2	a	1	1	beijing	1
3	a	1	1	beijing	1
5	a	1	1	beijing	0

  

方式3:cat command.sql | mysql -u -p

  這種方式其實等價於方式二,先將要執行的sql保存到文件中,此處仍為/tmp/command.sql;

$ cat /tmp/command.sql | mysql -uroot -p
Enter password:
id	name	age	gender	addr	status
1	a	1	1	beijing	1
2	a	1	1	beijing	1
3	a	1	1	beijing	1
5	a	1	1	beijing	0

  

命令行顯式指定操作的數據庫

  對於方式2和方式3來說,需要在sql文件中指定操作的數據庫,如果想要在命令行中指定數據庫,可以在命令行中增加數據庫名:

# 指定對test數據庫進行操作
$ mysql -uroot -p test < /tmp/command.sql
Enter password:
id	name	age	gender	addr	status
1	a	1	1	beijing	1
2	a	1	1	beijing	1
3	a	1	1	beijing	1
5	a	1	1	beijing	0

  雖然命令行指定了數據庫,但是sql文件中仍可以進行數據庫的切換,所以不建議在命令行中指定操作的數據庫。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM