参数说明
1 | -u 用户名 |
操作
说明: 使用ip时使用-h指定,以下不进行ip指定
1 | [root@node1 datasets]# mysql -udbuser -p1RootRoot@ -D school -e 'select * from Student' |
实例
写一个脚本,该脚本可以接收一个参数,参数为需要执行的SQI语句
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29[root@node1 shell]# sh example_1.sh school "select * from Student"
mysql: [Warning] Using a password on the command line interface can be insecure.
+-----+--------+
| Sno | Sname |
+-----+--------+
| 001 | 陈一 |
| 002 | 郭二 |
| 003 | 张三 |
| 004 | 李四 |
| 005 | 王五 |
+-----+--------+
[root@node1 shell]# sh example_1.sh school "select * from Student" > result.txt
mysql: [Warning] Using a password on the command line interface can be insecure.
[root@node1 shell]# cat result.txt
Sno Sname
001 陈一
002 郭二
003 张三
004 李四
005 王五
[root@node1 shell]# cat example_1.sh
#!/bin/bash
#
user="dbuser"
passwd="1RootRoot@"
host="192.168.37.101"
mysql -u$user -p$passwd -D $1 -e "$2"查询MySQL任意表的数据,并将查询到的结果保存到HTML文件中
1
2
3
4
5
6
7
8
9
10
11
12
13[root@node1 shell]# sh example_2.sh school "select * from Student" > result.html
mysql: [Warning] Using a password on the command line interface can be insecure.
[root@node1 shell]# cat result.html
<TABLE BORDER=1><TR><TH>Sno</TH><TH>Sname</TH></TR><TR><TD>001</TD><TD>陈一</TD></TR><TR><TD>002</TD><TD>郭二</TD></TR><TR><TD>003</TD><TD>张三</TD></TR><TR><TD>004</TD><TD>李四</TD></TR><TR><TD>005</TD><TD>王五</TD></TR></TABLE>[root@node1 shell]#
[root@node1 shell]# cat example_2.sh
#!/bin/bash
#
user="dbuser"
passwd="1RootRoot@"
host="192.168.37.101"
mysql -u$user -p$passwd -H -D $1 -e "$2"查询MySQL任意表的数据,并将查询到的结果保存到XML文件中
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41[root@node1 shell]# sh example_3.sh school "select * from Student" > result.xml
mysql: [Warning] Using a password on the command line interface can be insecure.
[root@node1 shell]# cat result.xml
<?xml version="1.0"?>
<resultset statement="select * from Student
" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<row>
<field name="Sno">001</field>
<field name="Sname">陈一</field>
</row>
<row>
<field name="Sno">002</field>
<field name="Sname">郭二</field>
</row>
<row>
<field name="Sno">003</field>
<field name="Sname">张三</field>
</row>
<row>
<field name="Sno">004</field>
<field name="Sname">李四</field>
</row>
<row>
<field name="Sno">005</field>
<field name="Sname">王五</field>
</row>
</resultset>
[root@node1 shell]# cat example_3.sh
#!/bin/bash
#
user="dbuser"
passwd="1RootRoot@"
host="192.168.37.101"
mysql -u$user -p$passwd -X -D $1 -e "$2"Shell脚本导入数据
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22# IFS可以指定read的分隔符
[root@node1 shell]# sh import.sh
[root@node1 shell]# cat import.sh
#!/bin/bash
#
user="dbuser"
passwd="1RootRoot@"
cat data.txt | while read id name
do
mysql -u$user -p$passwd -Dschool -e "insert into Student values('$id','$name')"
done
[root@node1 shell]# cat data.txt
110 Allen
122 Kilen
123 abc
124 qw
234 wew
345 wsd