如何只连接一次Mysql?

如何只连接一次Mysql?

我创建了一个 shell 脚本来连接到数据库并从 dhcpd.log 文件插入 IP 和 MAC,
脚本正常工作:

#/!bin/bash
#Defining Variables
dhcpLogFile="/var/log/dhcpd.log"

#Begin Code
# extrcting the Information of IPs and MACs from log file
# and eleminating the duplicate Entry
NumberOfLines=$(awk '/DHCPACK/ { print $8} ' $dhcpLogFile | awk '!x[$0]++'|awk 'BEGIN{i=0}{i++;}END{print i}')
j=1
while [ $NumberOfLines -gt 0 ]
do
ip=$(awk '/DHCPACK/ { print $8} ' $dhcpLogFile | awk '!x[$0]++' |cut -f$j -d$'\n')
mac=$(awk '/DHCPACK/ { print $10} ' $dhcpLogFile | awk '!x[$0]++' |cut -f$j -d$'\n')
echo $ip
echo $mac   
let "j +=1"
let "NumberOfLines -=1"
mysql -u root --password='pw' MatchingDB <<- _END_ 
INSERT INTO IP_MACTable (IP_Address, MAC) VALUES ('$ip','$mac');
_END_
done

代码是正确的,但正如您所看到的,它在每次插入查询时都连接到数据库,我的问题是如何仅连接到数据库一次,然后执行多个查询,然后退出而不在每次插入操作时连接到数据库

答案1

您可以通过管道到 mysql 来做到这一点:

while …
do
    echo "INSERT INTO IP_MACTable (IP_Address, MAC) VALUES ('$ip','$mac');"
done | mysql -u root …

请注意我如何更改while循环以将其想要运行的查询输出到标准输出。然后我将你的 while do...done 循环通过管道传输到mysql.

您也可以通过管道传输子外壳,例如您可以这样做:

(
    echo "BEGIN;"
    while … ; do
        echo "INSERT INTO IP_MACTable (IP_Address, MAC) VALUES ('$ip','$mac');"
    done
    echo "COMMIT;"
) | mysql -u root …

这样,如果您在中间中止处理,MySQL 将回滚事务,这样您就不会得到半加载的文件。此外,在事务内运行(而不是单独提交每一行)通常要快得多。

相关内容