Python-SQLite JSON1加载扩展

2024-05-14 04:30:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在Python中使用SQLite的json1扩展。根据official documentation,它应该是一个可加载的扩展。我从source中获取了json1.c文件,并按照official instructions将其编译为json1.c,没有任何错误。

$ gcc -g -fPIC -shared json1.c -o json1.so

当我试图根据sqlite3 documentation在Python 2.7.12(和3.5.2)中加载扩展时,出现了问题。

>>> import sqlite3
>>> con = sqlite3.connect(":memory:")
>>> con.enable_load_extension(True)
>>> con.load_extension("./json1.so")

我收到了以下回溯错误消息。我从包含json1.so文件的文件夹中运行了Python解释器。尽管看起来由于最后一个冒号应该有更多的信息,但下面是完整的错误消息。

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
sqlite3.OperationalError: error during initialization:

实际上不可能在Python中使用json1作为可加载的扩展吗?我唯一的选择是重新编译SQLite、pysqlite2等,如Charles Leifer在this博客文章中所解释的那样?

编辑:

结果,我收到了错误,因为我的机器已经启用了这个和其他扩展。启用已启用的扩展的操作触发了错误。到目前为止,我可以访问的所有linux计算机都已经在Python附带的SQLite中启用了json1和fts5扩展。通过连接到SQLite数据库并运行以下查询,可以检查使用了哪些编译选项。

PRAGMA compile_options;

Tags: 文件消息sourcesqlitesodocumentation错误extension
2条回答

对于仍在试图从源代码构建json1扩展的任何人,这里是:

SQLite Source Repository下载latest release source code后,将其解压缩,cd到其文件夹中并运行./configure

然后将以下内容添加到生成的Makefile

json1.dylib: json1.lo  
    $(LTCOMPILE) -c $(TOP)/ext/misc/json1.c  
    $(TCC) -shared -o json1.dylib json1.o  

make很挑剔,所以请确保$(LTCOMPILE)$(TCC)前面是制表符,而不是空格!

然后运行make json1.dylib

引用:https://burrows.svbtle.com/build-sqlite-json1-extension-as-shared-library-on-os-x

您可以使用python 3运行sqlite。以下是我的mac电脑的工作原理:

首先编译可加载扩展:

curl -O http://sqlite.org/2016/sqlite-src-3140100.zip 

unzip sqlite-src-3140100.zip

gcc -g -fPIC -dynamiclib sqlite-src-3140100/ext/misc/json1.c -o json1

然后在脚本中使用它:

import sqlite3
conn = sqlite3.connect('testingjson.db')

#load precompiled json1 extension
conn.enable_load_extension(True)
conn.load_extension("./json1")

# create a cursor
c = conn.cursor()

# make a table
# create table NAME_OF_TABLE (NAME_OF_FIELD TYPE_OF_FIELD);
c.execute('create table testtabledos (testfield JSON);')

# Insert a row of data into a table
c.execute("insert into testtabledos (testfield) values (json('{\"json1\": \"works\"}'));")

# Save (commit) the changes
conn.commit()

# We can also close the connection if we are done with it.
# Just be sure any changes have been committed or they will be lost.
conn.close()

或者在贝壳里:

.load json1
CREATE TABLE test_table (id INTEGER, json_field JSON);
# insert data into test table
insert into test_table (id, json_field) values (1, json('{"name":"yvan"}'));
insert into test_table (id, json_field) values (2, json('{"name":"sara"}'));
#select json objects from the json column
select * from test_table where json_extract("json_field", '$.name') is not null;
1|{"name":"yvan"}
2|{"name":"sara"}

我希望这更容易。似乎加载扩展(而不是在创建时将它们构建到sqlite)更有意义。我最近的问题是,我似乎无法在CentOS 6上编译json1扩展。

我在这里写了一本指南:https://github.com/SMAPPNYU/smapphowto/blob/master/howto_get_going_with_sqlite_json1.md

编辑:为了我的目的,我最终放弃了json1。我现在只需要使用pysmap dump_to_csv来提取我想要的字段,然后dump_to_sqlite_db从该csv创建一个普通的sqlite数据库。见pysmap smapp_collection

相关问题 更多 >