在SQLite数据库中存储XML/HTML文件 - 可行吗?

5 投票
1 回答
9154 浏览
提问于 2025-04-16 00:44

可以直接把一个XML/HTML文件存到SQLite数据库里吗?

我正在用Python写一个程序,这个程序需要解析XML/HTML文件,并把里面的值存到数据库里。不过,XML/HTML文件里的字段可能会不一样,我觉得直接把整个文件存到数据库里会更简单,然后在需要的时候再解析它。

用Python和SQLite可以这样做吗?还是我这个思路有问题?

谢谢大家!

补充:有没有人能分享一下怎么存这个文件的代码示例?我知道这是可行的,但我不太确定该怎么做。

1 个回答

7

你可以把你的XML或HTML文件当作文本存储在文本列里,这样没有问题。

不过明显的缺点是,你不能直接查询XML里的值。

补充说明:这里有个例子。你只需要把XML文件读入一个变量,然后像存储其他字符串一样把它存到数据库里,和你想存的其他值一起存。当你想使用这个XML时,只需从数据库中读取它,然后用XML解析器解析一下。

# connect to database and create table
import sqlite3
conn = sqlite3.connect(":memory:")
conn.execute('''create table my_table (value1 integer, value2 integer, xml text)''')

# read text from your input file containing xml
f = file('/tmp/my_file.xml')
xml_string_from_file = f.read()

# insert text into database
cur = conn.cursor()
cur.execute('''insert into my_table (value1, value2, xml) values (?, ?, ?)''', (23, 42, xml_string_from_file))
conn.commit()

# read from database into variable
cur.execute('''select * from my_table''')
xml_string_from_db = cur.fetchone()[2]

# parse with the XML parser of your choice
from xml.dom.minidom import parseString
dom = parseString(xml_string_from_db)

撰写回答