我在将值插入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中执行此操作。有人可以帮忙吗?
标记名称中有2种错字,用于从XML中提取数据。
# 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");
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句