首页 > 解决方案 > SQLITE_CANTOPEN - nodejs-mobile

问题描述

错误:SQLITE_CANTOPEN

var sqlite3 = require('sqlite3').verbose();
var db = new sqlite3.Database('MyDB.db', sqlite3.OPEN_READWRITE | sqlite3.OPEN_CREATE);
db.serialize(function() {
  db.run("CREATE TABLE lorem (info TEXT)");

  var stmt = db.prepare("INSERT INTO lorem VALUES (?)");
  for (var i = 0; i < 10; i++) {
      stmt.run("Ipsum " + i);
  }
  stmt.finalize();

  db.all("SELECT rowid AS id, info FROM lorem", function(err, rows) {
    rn_bridge.channel.send(rows);
  });

});

我在以下环境中运行它:https ://github.com/janeasystems/nodejs-mobile react native

在 node.js 上下文中运行没有 rn_bridge.channel.send(rows) 和 console.lognode index.js工作正常。

标签: node.jssqlitereact-native

解决方案


The issue is likely that sqlite3 is internally using the Current Working Directory for this, which is not a path would be writable in iOS / Android applications.

Using the rn_bridge.app.datadir() API would be the way to have a writable location. https://github.com/JaneaSystems/nodejs-mobile-react-native/tree/49c069539db138688a9e44c44180bb0c3335537c#rn_bridgeappdatadir

Something like this would be the way to do it:

const path = require('path');
var sqlite3 = require('sqlite3').verbose();
var db_path= path.join(cordova.app.datadir(), 'MyDB.db');
var db = new sqlite3.Database(db_path, sqlite3.OPEN_READWRITE | sqlite3.OPEN_CREATE);

推荐阅读