BASH,将变量传递给sqlite

时间:2015-04-27 19:03:18

标签: bash sqlite

我试图将在bash中创建的变量传递给sqlite命令字符串。我可以看到我正在尝试将artist_id(外键)写入artist_id中的songs表中。我可以从艺术家表中检索出artist_id字段。当我尝试使用变量$ artist_id在歌曲表中创建一个新记录时,我收到一个错误;

  

错误:FOREIGN KEY约束失败

它肯定是正确的密钥,在这种情况下为4,但sqlite似乎不接受它所以我认为这可能是一个格式化问题?我尝试删除引号,添加'..etc。但没有快乐,任何想法?

artistcheck=$(sqlite3 "$dbFile" "$forkey SELECT EXISTS(SELECT 1 FROM artists WHERE artist_name='${ARRAY[2]}' LIMIT 1);")
if [ "$artistcheck" -eq 1 ]; then
    artistid=$(sqlite3 "$dbFile" "$forkey SELECT artist_id FROM artists WHERE artist_name='${ARRAY[2]}';")
  echo "Yep, "${ARRAY[2]}" exists and the id is $artistid."
else
    echo "Nope, "${ARRAY[2]}" doesnt exist"
    sqlite3 "$dbFile" "$forkey INSERT INTO artists (artist_name) VALUES ('${ARRAY[2]}');"
    artistid=$(sqlite3 "$dbFile" "$forkey SELECT artist_id FROM artists WHERE artist_name='${ARRAY[2]}';")
    echo "New Artist created. Name: ${ARRAY[2]} and ID is $artistid."
fi

songcheck=$(sqlite3 "$dbFile" "$forkey SELECT EXISTS(SELECT 1 FROM songs WHERE song_name='${ARRAY[1]}' AND artist_id='$artistid' LIMIT 1);")
if [ "$songcheck" -eq 1 ]; then
    songid=$(sqlite3 "$dbFile" "$forkey SELECT song_id FROM songs WHERE song_name='${ARRAY[1]}' AND artist_id='$artistid';")
  echo "Yep, "${ARRAY[1]}" exists and the song ID is $songid and the artist id is $artistid."
else
  echo "Nope, "${ARRAY[1]}" doesnt exist"
  sqlite3 "$dbFile" "$forkey INSERT INTO songs (artist_id, song_name) VALUES ('$artist_id','${ARRAY[2]}');"
  songid=$(sqlite3 "$dbFile" "$forkey SELECT song_id FROM songs WHERE song_name='${ARRAY[1]}' AND artist_id='$artist_id';")
  echo "New Song created. Name: ${ARRAY[1]} and song ID is $songid and the artist id is $artistid."
fi

1 个答案:

答案 0 :(得分:0)

将变量$ artistid与字段' artist_id'混合。在sql语句中。从底部第4行我相信。道德:使用有意义的变量名称并消除咖啡因。