从MySQL TEXT类型以相同格式检索数据

时间:2019-01-25 08:56:04

标签: mysql sql bash openvpn

我有一个脚本,可以将文本文件保存到MySQL中。这是表格的结构:

create table save( 
    id INT(10) NOT NULL AUTO_INCREMENT,
    client_name VARCHAR(255) NOT NULL,
    file_txt TEXT NOT NULL,
    primary key (id) 
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

在以下脚本中,我可以向该表中添加数据:

#!/bin/bash
DB_USER="root"
DB_PASSWD=""
DB_NAME="test_save"
TABLE="save"

if [ $# -eq 1 ]; then
    client="$1"
    file=`cat /path/to/the/file`
    mysql --user=$DB_USER --password=$DB_PASSWD $DB_NAME << EOF
        INSERT INTO $TABLE (client_name, file_txt) VALUES ("$client", "$file");
EOF
else
    echo "Missing client name"
fi

这是file(这是一个openVPN文件)的原始内容:

client
proto udp
remote IPADRESS PORT
dev tun
resolv-retry infinite
nobind
persist-key
persist-tun
remote-cert-tls server
verify-x509-name server_3sO2TzCVUQf73j0R name
auth SHA256
auth-nocache
cipher AES-128-GCM
tls-client
tls-version-min 1.2
tls-cipher TLS-ECDHE-ECDSA-WITH-AES-128-GCM-SHA256
setenv opt block-outside-dns
verb 0
<ca>
-----BEGIN CERTIFICATE-----
SOME KEY
-----END CERTIFICATE-----
</ca>
<cert>
-----BEGIN CERTIFICATE-----
SOME KEY
-----END CERTIFICATE-----
</cert>
<key>
-----BEGIN PRIVATE KEY-----
SOME KEY
-----END PRIVATE KEY-----
</key>
key-direction 1
<tls-auth>
#
# 2048 bit OpenVPN static key
#
-----BEGIN OpenVPN Static key V1-----
SOME KEY
-----END OpenVPN Static key V1-----
</tls-auth>

因此,借助脚本,我成功地将文件的内容添加到了数据库中。


当我尝试使用另一个脚本检索数据时:

#!/bin/bash
DB_USER="root"
DB_PASSWD=""
DB_NAME="test_save"
TABLE="save"

if [ $# -eq 1 ]; then
    client="$1"
    content_file=$(echo "SELECT file_txt FROM $TABLE WHERE client_name='$client'" | mysql $DB_NAME -u $DB_USER -p$DB_PASSWD)
    echo "$content_file" >> new_file

else
    echo "Missing client name"
fi

但是当我打开new_file时,我得到以下信息:

ovpn
client\nproto udp\nremote IPADRESS PORT\ndev tun\nresolv-retry infinite\nnobind\npersist-key\npersist-tun\nremote-cert-tls server\nverify-x509-name server_3sO2TzCVUQf73j0R name\nauth SHA256\nauth-nocache\ncipher AES-128-GCM\ntls-client\ntls-version-min 1.2\ntls-cipher TLS-ECDHE-ECDSA-WITH-AES-128-GCM-SHA256\nsetenv opt block-outside-dns \nverb 0\n<ca>\n-----BEGIN CERTIFICATE-----\nSOME KEY\n-----END CERTIFICATE-----\n</ca>\n<cert>\n-----BEGIN CERTIFICATE-----\nSOME KEY\n-----END CERTIFICATE-----\n</cert>\n<key>\n-----BEGIN PRIVATE KEY-----\nSOME KEY\n-----END PRIVATE KEY-----\n</key>\nkey-direction 1\n<tls-auth>\n#\n# 2048 bit OpenVPN static key\n#\n-----BEGIN OpenVPN Static key V1-----\nSOME KEY\n-----END OpenVPN Static key V1-----\n</tls-auth>

所以我不知道如何以相同的格式检索它。还是应该将文件存储为BLOB类型?

1 个答案:

答案 0 :(得分:1)

用“相同格式”表示您不希望它不显示在1行上吗? 如果是这样,您可以尝试替换:

echo "$content_file" >> new_file

具有:

echo -e "$content_file" >> new_file

-e选项应正确地将'\ n'转换为新行