shell腳本與mysql交互方法匯總
shell腳本導入數據文件到mysql內
當然是利用mysqlimport啦.
示例腳本:
01
#!/bin/sh
02
# import test_table.sql into test_database.test_table
03
# content in test_table.sql like "123,abc,334; N,ddd,999"
04 www.2cto.com
05
### define constant
06
MYSQL_IP=192.168.0.69
07
MYSQL_USER=root
08
MYSQL_PW=root
09
MYSQL_DATABASE=test_database
10
MYSQL_TABLE=test_table
11
12
function import_from_file()
13
{
14
echo "開始導入<${MYSQL_TABLE}.sql>到<${MYSQL_IP}/${MYSQL_DATABASE}> ..."
15
echo -n -e "\t"
16
mysqlimport -h ${MYSQL_IP} -u${MYSQL_USER} -p${MYSQL_PW} --fields-terminated-by=',' --lines-terminated-by=';' -L ${MYSQL_DATABASE} ${MYSQL_TABLE}.sql
17
if [ 0 -eq $? ]; then
18
echo "導入完成!"
19 www.2cto.com
else
20
echo "導入過程中出現錯誤,錯誤碼為:$?"
21
exit
22
fi
23
echo
24
}
25
26
# call function
27
import_from_file
shell腳本中使用mysql命令
方法一:
1
#!/bin/sh
2
CONNECT_MYSQL="mysql -h 192.168.0.123 -uroot -p123456 test_database"
3
SQL="SELECT * FROM TEST_TABLE"
4
5
echo "${SQL}" | ${CONNECT_MYSQL}
方法二:
1
#!/bin/sh
2 www.2cto.com
CONNECT_MYSQL="mysql -h 192.168.0.123 -uroot -p123456 test_database"
3
SQL="SELECT * FROM TEST_TABLE"
4
5
echo ${CONNECT_MYSQL} <<MYSQLEOF
6
${SQL}
7
MYSQLEOF