简体   繁体   English

在python3 sqlite中加载sqlite3扩展

[英]Load sqlite3 extension in python3 sqlite

How does one correctly load a sqlite extension into python sqlite import? 如何正确将sqlite扩展加载到python sqlite导入中?

os: Windows 7 64bit 操作系统:Windows 7 64bit
sqlite3 version: 3.14.1 64bit sqlite3版本:3.14.1 64bit
python3 version: 3.5.2 64bit python3版本:3.5.2 64bit

Here is my process so far: compile extension-functions.c to libsqlitefunctions.dll using this command: 到目前为止,这是我的过程:使用以下命令将extension-functions.c编译为libsqlitefunctions.dll:

gcc -shared -I "C:\Software\sqlite3\sqlite-master" -o libsqlitefunctions.dll extension-functions.c

Then I can happily use these functions in sqlite3 command line using this command: 然后,我可以使用以下命令在sqlite3命令行中愉快地使用这些功能:

SELECT load_extension('libsqlitefunctions.dll');

However when trying in the python script: 但是,当尝试使用python脚本时:

import sqlite3 as lite
con = lite.connect(db_file)
con.enable_load_extension(True)
con.load_extension("<<path to file>>\\libsqlitefunctions.dll")

This error appears: 出现此错误:

Error The specified module could not be found. 错误找不到指定的模块。 :

The extension-functions.c file does include the COMPILE_SQLITE_EXTENSIONS_AS_LOADABLE_MODULE section, and in fact it loads fine when using command line sqlite3 extension-functions.c文件的确包含COMPILE_SQLITE_EXTENSIONS_AS_LOADABLE_MODULE部分,实际上,在使用命令行sqlite3时它可以很好地加载

Additional notes: 补充笔记:
The python sqlite package is installed and working correctly. python sqlite软件包已安装并正常运行。
I've also tried updating the sqlite3.dll in the python path to the latest version 我也尝试将python路径中的sqlite3.dll更新为最新版本

This isn't a nice answer, but it provides a method to use the extension in python. 这不是一个很好的答案,但是它提供了一种在python中使用扩展名的方法。

Output sql commands to a file, then use subprocess to run the file directly into the command line, like so: 将sql命令输出到文件,然后使用子进程将文件直接运行到命令行中,如下所示:

import subprocess
import uuid
import os

db_file = "trial02.db"
sqlite_functions_file = "libsqlitefunctions.dll"

sql_file = uuid.uuid4() + ".sql"
with open(sql_file, 'w') as fsql:
    fsql.write('/* auto script */\n\n')
    #load extension
    sql = "SELECT load_extension('" + sqlite_functions_file + "');"
    fsql.write(sql + '\n')
    #sql scripts
    sql = "insert into t(c) values (log(2));"
    fsql.write(sql + '\n')

args = [
    'sqlite3'
    , db_file
    , '< ', sql_file
]
print(' '.join(args))
out1 = subprocess.run(' '.join(args), shell=True)
os.remove(sql_file)

Place libsqlitefunctions.dll in a folder that is visible globally like c:\\WINDOWS\\ or some other folder from the PATH environment variable. libsqlitefunctions.dll放在全局可见的文件夹中,例如c:\\WINDOWS\\PATH环境变量中的某些其他文件夹。 Then you will be able to load the extension using simple command: 然后,您将可以使用简单的命令加载扩展:

con.load_extension("libsqlitefunctions.dll")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM