我正在尝试使用sqlite数据库(例如data.db)并在HTML页面中显示。如果我可以在表格中显示那将是伟大的。但是现在,我只是想看看数据。到目前为止,我已经尝试了所有我能找到的东西。
我使用sql.js作为框架,下面是我的代码。
<html>
<head>
<title>Title</title>
<script type="text/javascript" src="https://raw.githubusercontent.com/kripken/sql.js/master/js/sql.js"></script>
<script type="text/javascript" src="https://raw.githubusercontent.com/kripken/sql.js/master/js/worker.sql.js"></script>
<script src='sql.js'></script>
<script type="text/javascript">
var xhr = new XMLHttpRequest();
xhr.open('GET', 'data.db', 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");
};
xhr.send();
</script>
</head>
<body>
<h1>Database Data</h1>
...data to display here...
一切都会有所帮助。
答案 0 :(得分:0)
我希望你已经找到了答案,所以我的答案仅适用于后人。我花了一段时间才找到解决方案,但代码应该引导您找到解决方案。
<html>
<head>
<title>Title</title>
<script type="text/javascript" src="https://raw.githubusercontent.com/kripken/sql.js/master/js/sql.js"></script>
<script type="text/javascript" src="https://raw.githubusercontent.com/kripken/sql.js/master/js/worker.sql.js"></script>
<!--
<script type="text/javascript" src="sql.js"></script>
<script type="text/javascript" src="worker.sql.js"></script>
-->
<script type="text/javascript">
var path = "http://alasql.org/demo/016sqlite/Chinook_Sqlite.sqlite";
//var path = "016sqlite_files/Chinook_Sqlite.sqlite"
var xhr = new XMLHttpRequest();
xhr.open('GET', path, 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 name FROM sqlite_master where type='table'");
var contents = db.exec("SELECT * FROM Playlist");
//alert(JSON.stringify(contents));
var table_string = '<table>';
if (contents) {
table_string += '<tr>';
for (var index in contents[0].columns) {
table_string += '<th>' + contents[0].columns[index] + '</th>';
}
table_string += '</tr>';
for (var row_index in contents[0].values) {
table_string += '<tr>';
for (var col_index in contents[0].values[row_index]) {
table_string += '<td>' + contents[0].values[row_index][col_index] + '</td>';
}
table_string += '</tr>';
}
}
table_string += '</table>';
//alert(table_string);
document.getElementById("res").innerHTML = table_string;
}
xhr.send();
</script>
</head>
<body>
<h1>Database Data</h1>
<p id="res"></p>
</body>
</html>
对于某些快速错误检查,我使用了本地文件,但代码应该按原样运行。这些链接可以帮助您进一步:
https://github.com/kripken/sql.js/issues/207 https://github.com/kripken/sql.js/blob/master/README.md