有没有办法从octave读写sqlite3?
我正在考虑 R 中的 RODBC 或 python 中的 sqlite3 包,但针对 Octave 。
我查看了 octave-forge http://octave.sourceforge.net/packages.php
但是只能找到只支持postgresql的'database'包。
详细信息:
- 操作系统:Ubuntu 12.04
- Octave :3.6.2
- sqlite:3.7.9
最佳答案
我意识到这是一个老问题,但这里的大多数答案似乎都没有捕获重点,关注是否存在提供正式接口(interface)的定制 Octave 包,而不是是否有可能从 Octave 内执行 sqlite3 查询首先。
因此,我想我会为任何想通过 Octave 访问 sqlite3 的人提供一个实用的答案;这样做实际上是微不足道的,我自己也这样做过很多次。
只需对 sqlite3
命令进行适当的系统调用(显然这意味着您的系统上安装了 sqlite3 客户端)。我发现最方便的方法是使用
sqlite3 database.sqlite < FileContainingQuery > OutputToFile
调用 sqlite3 的语法。
任何修改输出的 sqlite3 命令都可以与查询一起传递,以获得所需格式的输出。
例如这是一个从表中绘制频率图的玩具示例,该表以 csv 格式返回适当的分数和计数(从输出中删除标题和运行时统计信息)。
pkg load io % required for csv2cell (used to collect results)
% Define database and Query
Database = '/absolute/path/to/database.sqlite';
Query = strcat(
% Options to sqlite3 modifying output format:
".timer off \n", % Prevents runtime stats printed at end of query
".headers off \n", % If you just want the output without headers
".mode csv \n", % Export as csv; use csv2cell to collect results
% actual query
"SELECT Scores, Counts \n",
"FROM Data; \n" % (Don't forget the semicolon!)
);
% Create temporary files to hold query and results
QueryFile = tempname() ; QueryFId = fopen( QueryFile, 'w' );
fprintf( QueryFId, Query ); fclose( QueryFId);
ResultsFile = tempname();
% Run query
Cmd = sprintf( 'sqlite3 "%s" < "%s" > "%s"', Database, QueryFile, ResultsFile );
[Status, Output] = system( Cmd );
% Confirm query succeeded and if so collect Results
% in a cell array and clean up temp files.
if Status != 0, delete( QueryFile, ResultsFile ); error("Query Failed");
else, Results = csv2cell( ResultsFile ); delete( QueryFile, ResultsFile );
end
% Process Results
Results = cell2mat( Results );
Scores = Results(:, 1); Counts = Results(:, 2);
BarChart = bar( Scores, Counts, 0.7 ); % ... etc
等等,瞧
关于database - 我可以使用 Octave 访问 sqlite3 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14922186/