从数组中设置mysql语句中的列和值

sycxhyv7  于 2021-06-23  发布在  Mysql
关注(0)|答案(1)|浏览(271)

是否可以将mysql查询中的列和值设置为一组可以更改大小和内容的数组?我想过使用循环,但我意识到我能想出如何使用短语

mysql -u$user -p$password -h$host $database<<EOFMYSQL 
INSERT INTO customers (${ArrayA[0]}, ${ArrayA[1]}, ${ArrayA[2]}, ${ArrayA[3]})
VALUES ('${Array2[0]}' , '${ArrayB[1]}' , '${ArrayB[2]}' , '${ArrayB[3]}')
EOFMYSQL

循环思想

mysql -u$user -p$password -h$host $database<<EOFMYSQL 
for (( c=0; c<=${#ArrayA[@]}; c++ ))
do
echo $c
INSERT INTO Customers (${ArrayA[$c]})
VALUES ('${ArrayB[$c]}')
done
EOFMYSQL

有什么建议吗?

eiee3dmh

eiee3dmh1#

在bash中使用数组时可以尝试这样的方法。。。

fields=(field1 field2 field3)
vals=("val1" "val2" "val3")

nvals=()

# need to add the single quotes around the values

for v in "${vals[@]}"; do nvals+=("'$v'"); done

# keep the old value of IFS so we can reset it.  Of course, if this is

# being done in a script this may not be necessary.

oldifs=$IFS

# set bash's word separator to a comma so that is included in the expansions

IFS=','
into="${fields[*]}"
values="${nvals[*]}"
echo "$into"
echo "$values"
IFS=$oldifs

# this is just to show the expansion with the original IFS

into="${fields[*]}"
echo "back to regular IFS:"
echo "$into"

结果是: field1,field2,field3 'val1','val2','val3' back to regular IFS: field1 field2 field3 带有[*]的数组扩展只使用ifs变量(用于分隔单词的标准bash变量)的第一个字符,因此我无法添加任何空格来提高可读性。当然,这当前会忽略包含非标准字符和带有单引号的值的字段。
我还发现我必须将扩展设置为一个变量(into和values),以便正确地进行扩展,我不能只回显数组,比如 echo "${into[*]}"

相关问题