How to fetch server-side sqlite database to user-side in order to make use of “sql.js”?

时间:2022-05-26 16:52:17

I found this tool called "sql.js" that can access sqlite database directly from javascript. But in order to use it, the user-side has to have the sqlite database file first. In my situation, the database is maintained at the server-side. So here is my question: how do I move the sqlite database file from the server-side to the user-side-javascript so that user-side can make use of this "sql.js" to access the database? Is it possible to do in an Ajax call? Any sample code would be really appreciated!

我发现这个名为“sql.js”的工具可以直接从javascript访问sqlite数据库。但是为了使用它,用户端必须首先拥有sqlite数据库文件。在我的情况下,数据库是在服务器端维护的。所以这是我的问题:如何将sqlite数据库文件从服务器端移动到用户端javascript,以便用户端可以使用这个“sql.js”来访问数据库?是否可以在Ajax调用中执行?任何示例代码都将非常感谢!

1 个解决方案

#1


0  

Think this example in the docs wasn't added at the time the question was asked:

认为在提出问题时未添加文档中的此示例:

<script src='js/sql.js'></script>
<script>
var xhr = new XMLHttpRequest();
xhr.open('GET', '/path/to/database.sqlite', true);
xhr.responseType = 'arraybuffer';

xhr.onload = function(e) {
  var uInt8Array = new Uint8Array(this.response);
  var db = new SQL.Database(uInt8Array);
  var contents = db.exec("SELECT * FROM my_table");
  // contents is now [{columns:['col1','col2',...], values:[[first row], [second row], ...]}]
};
  xhr.send();
</script>

Bear in mind that if your database is large, SQL.js probably isn't suitable.

请记住,如果您的数据库很大,SQL.js可能不适合。

(Partly because you'll have to transfer the database to the user, and partly because SQL.js is memory hungry, so you may be better running the queries on the server anyway.)

(部分原因是你必须将数据库传输给用户,部分原因是因为SQL.js需要内存,所以无论如何你最好在服务器上运行查询。)

#1


0  

Think this example in the docs wasn't added at the time the question was asked:

认为在提出问题时未添加文档中的此示例:

<script src='js/sql.js'></script>
<script>
var xhr = new XMLHttpRequest();
xhr.open('GET', '/path/to/database.sqlite', true);
xhr.responseType = 'arraybuffer';

xhr.onload = function(e) {
  var uInt8Array = new Uint8Array(this.response);
  var db = new SQL.Database(uInt8Array);
  var contents = db.exec("SELECT * FROM my_table");
  // contents is now [{columns:['col1','col2',...], values:[[first row], [second row], ...]}]
};
  xhr.send();
</script>

Bear in mind that if your database is large, SQL.js probably isn't suitable.

请记住,如果您的数据库很大,SQL.js可能不适合。

(Partly because you'll have to transfer the database to the user, and partly because SQL.js is memory hungry, so you may be better running the queries on the server anyway.)

(部分原因是你必须将数据库传输给用户,部分原因是因为SQL.js需要内存,所以无论如何你最好在服务器上运行查询。)