2016-09-16 52 views
1

我想要一個sqlite數據庫(例如data.db)並顯示在HTML頁面中。如果我能在桌上展示那將會很棒。但現在,我只想看看數據。到目前爲止,我已經嘗試了一切我能找到使用sql.js在HTML頁面中顯示SQLite .db

我正在使用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

我希望你已經找到了答案,所以我的答案只是爲了後代。我花了一段時間才找到一個解決方案,但代碼應該指導您解決問題。

<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