Friday, March 28, 2014

Get value from sqlite3 db file through javascript

Sqlite3:

For getting values from sqlite3 db through , we will in need of a sql.js file.

Steps for getting values:

1. Include sql.js file in your html file

2. Use following scripts:


<html>
<head>
  <title>
    sql.js
  </title>
  <script src="../js/sql.js"></script>
  <script>
    function readfile(){
      if (window.XMLHttpRequest)
        {// code for IE7+, Firefox, Chrome, Opera, Safari
          xmlhttp=new XMLHttpRequest();
        }
        else
        {// code for IE6, IE5
          xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.open("GET","path_of_db_file",false);
        xmlhttp.overrideMimeType('text/plain; charset=x-user-defined');
        xmlhttp.send();
        var xmlDoc=xmlhttp.responseText;
        return xmlDoc;
      }

    function bin2Array(bin) {
      'use strict';
      var i, size = bin.length, ary = [];
      for (i = 0; i < size; i++) {
        ary.push(bin.charCodeAt(i) & 0xFF);
      }
      return ary;
    }

    function print(text) {
      var element = document.getElementById('output');
      element.innerHTML = text;
    }

    var dbBin = readfile();
    var db = SQL.open(bin2Array(dbBin));
    function execute() {
      try {
        var data = db.exec('SELECT name FROM projects;');
        var get_value = JSON.stringify(data, null, '  ');
        print(get_value);
      } catch(e) {
        print(e);
      }
    }
  </script>
</head>
<body>
  <input type="submit" value="Get value" onclick="execute()">
  <div id="output"></div>
</body>
</html>

No comments:

Post a Comment