database - 使用 bash 将值插入 sqlite 数据库
问题描述
我在将值插入 sqlite 数据库时遇到问题。我正在使用 bash 脚本来解析 xml 文件,然后将这些值插入到数据库中。我的脚本如下:
#!/bin/bash
create_books_db()
{
sqlite3 books.db <<EOF
create table books (
book_id primary key,
book_url text,
description text,
book_name text
);
EOF
}
plug_values_into_books_db()
{
sqlite3 books.db <<EOF
insert into books (book_id,book_url,description,book_name)
values('$book_id',"$book_url","$description","$book_name");
EOF
}
start of script
create_books_db
line="/home/$USER/star.wars.the.empire.strikes.back.xml"
book_id=$(xmlstarlet sel -t -v //book/id $line);
book_url=$(xmlstarlet sel -t -v //book/book_url $line);
description=$(xmlstarlet sel -t -v //book/description $line);
book_name=$(xmlstarlet sel -t -v //book/name $line);
plug_values_into_books_db
#end of script
这是我正在使用的 xml 文件的示例:
?xml version="1.0"?>
<book>
<book_url>https://starwars.com/books/</book_url>
<character_credits>
<character>
<character_id>99</character_id>
<character_name>Darth Vader</character_name>
</character>
</character_credits>
<description> The Empire Strikes Back (also known as Star Wars: Episode V – The
Empire Strikes Back) is a 1980 American epic space-opera film directed
by Irvin Kershner. Leigh Brackett and Lawrence Kasdan wrote the
screenplay, with George Lucas writing the film's story and serving as
executive producer. It was produced by Gary Kurtz for Lucasfilm and
stars Mark Hamill, Harrison Ford, Carrie Fisher, Billy Dee Williams,
Anthony Daniels, David Prowse, Kenny Baker, Peter Mayhew, and Frank Oz.
It is the second installment in the original Star Wars trilogy, the
second of the franchise to be produced, and the fifth episode in the
“Skywalker Saga.”</description>
<book_id>103</book_id>
<book_name>The Empire Strikes Back</book_name>
</book>
1)当我在值行中尝试这个时:
值($book_id,"$book_url","$description","$book_name");
然后从sqlite中的书籍中选择*,缺少book_id和book_name值
2)在值行中更改为单引号会产生此错误:
错误:第 2 行附近:“s”附近:语法错误
3)转义引号会产生:
错误:第 2 行附近:无法识别的令牌:“\”
我也尝试在 bash 变量周围加上“'”引号,但我不断收到错误
只有第 1) 点上面的作品没有错误,但它似乎省略了 book_id 和 book_name 标签,
我正在学习sqlite,我认为这与在插入之前转义或清理输入有关,但我不知道如何在bash中做到这一点。任何人都可以帮忙吗?
解决方案
用于从 XML 中提取数据的标记名称中有 2 个拼写错误。
# Was book/id
book_id=$(xmlstarlet sel -t -v //book/book_id $line);
book_url=$(xmlstarlet sel -t -v //book/book_url $line);
description=$(xmlstarlet sel -t -v //book/description $line);
# Was book/name
book_name=$(xmlstarlet sel -t -v //book/book_name $line);
这应该使插入按预期工作。
建议:为保持一致性,book_id 使用双引号。请注意,双引号必须用于描述,因为它包含单引号,如film's
.
values("$book_id","$book_url","$description","$book_name");
推荐阅读
- django - Django ORM 在 15 分钟的时间块内获取数据的平均值
- ios - IQKeyboardManager:是否可以更改 UITextField 和键盘之间的距离?
- ajax - Ajax 调用未在 tomcat 8 中命中 servlet
- javascript - 只要鼠标悬停在 React 中的元素上,就会改变状态
- javascript - 在 Angular/Ionic 中将字符串编码为 cp852 - iconv-lite
- c# - WPF MVVM 树视图移动节点
- embedded - STM32 SPI MISO 保持高电平
- android - 使用 AWS DynamoDB 在 Android 应用程序中使用多个表
- javascript - jquery - 只允许在字段中验证负数、正数或小数
- python - 是否可以在通过 sklearn 创建的决策树分类器中手动更改拆分值