我的 Google 云端硬盘中有一个 sqlite3 文件,我想从 Google 云端硬盘中的电子表格设置 Google Apps 脚本,以读取该 SQLite 文件数据库并填充一些行。关于如何实现这一目标有什么想法吗?
编辑:
我设法使用带有异步 JavaScript 调用的附加 html 页面来查询 SQLite 文件。
function onOpen() {
const ui = SpreadsheetApp.getUi();
ui.createMenu('Integrations')
.addItem('SQLite','sqlite')
.addToUi();
}
function sqlite() {
const ui = SpreadsheetApp.getUi();
const html = HtmlService.createHtmlOutputFromFile('sqlite').setTitle('SQLite');
ui.showModalDialog(html, ' ');
}
function getDriveFile() {
return DriveApp.getFilesByName('filename.db').next().getBlob().getBytes();
}
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/sql-wasm.min.js"></script>
<script>
// Async call to the DriveApp that loads the SQLite file
let SQL, db, file;
(async() => {
SQL = await initSqlJs({ locateFile: file => 'https://cdn.jsdelivr.net/npm/[email protected]/dist/' + file });
google.script.run.withSuccessHandler(buffer => {
db = new SQL.Database(new Uint8Array(buffer));
const stmt = db.prepare("SELECT * FROM TABLE WHERE ID=:id");
const result = stmt.getAsObject({':id' : 1});
console.log(result);
//how can I pass the result back to the main gs file?
google.script.host.close()
}).getDriveFile();
})();
</script>
</head>
<body>
...
</body>
</html>
好的,这种方法有效,不确定是最好的方法,但对于我的小应用程序来说已经足够了。感谢大家的投入。
let jsResult;
function onOpen() {
const ui = SpreadsheetApp.getUi();
ui.createMenu('Integrations')
.addItem('SQLite','sqlite')
.addToUi();
}
function sqlite() {
const ui = SpreadsheetApp.getUi();
const html = HtmlService.createHtmlOutputFromFile('sqlite').setTitle('SQLite');
ui.showModalDialog(html, ' ');
}
function getDriveFile() {
return DriveApp.getFilesByName('filename.db').next().getBlob().getBytes();
}
function passResult(result) {
jsResult = result;
Browser.msgBox(result);
}
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/sql-wasm.min.js"></script>
<script>
// Async call to the DriveApp that loads the SQLite file
let SQL, db, file;
(async() => {
SQL = await initSqlJs({ locateFile: file => 'https://cdn.jsdelivr.net/npm/[email protected]/dist/' + file });
google.script.run.withSuccessHandler(buffer => {
db = new SQL.Database(new Uint8Array(buffer));
const stmt = db.prepare("SELECT * FROM TABLE WHERE ID=:id");
const result = stmt.getAsObject({':id' : 1});
google.script.run.withSuccessHandler(google.script.host.close)
.passResult(result);
}).getDriveFile();
})();
</script>
</head>
<body>
...
</body>
</html>
非常感谢 OP 分享他们的解决方案!
只是为了添加我这些天在 iOS Safari 浏览器上使用它时的发现......
google.script.run.withSuccessHandler(google.script.host.close).passResult(result);
google.script.run.withSuccessHandler(google.script.host.close).passResult(JSON.stringify(result));
const parsedResult = JSON.parse(result);