简体   繁体   中英

SQLite database in Javascript locally

I'm using a PhoneGap project on XCode. I am trying to connect to a SQLite databse by using Javascript.

I have made a file "myDatabase.sqlite" in an SQLite tool. Now my question is how do I open that database in my code? Right now I'm using the following code:

var db; 
var shortName = 'myDatabase'; 
var version = '1.0'; 
var displayName = 'myDatabase'; 
var maxSize = 65535; 


db = openDatabase(shortName, version, displayName,maxSize); 

db.transaction(function(transaction) {
    transaction.executeSql('SELECT * FROM User;', [],
    function(transaction, result) {

        if (result != null && result.rows != null) {
            for (var i = 0; i < result.rows.length; i++) {
                var row = result.rows.item(i);
                alert(row.ID);
            }
        }
    }, errorHandler);
}, errorHandler, nullHandler);

The problem is that the database is empty because when i run it it gives the error 'No such table'. I think it created a new database named "myDatabase" and thats why it has no tables.

Does anyone know how I can open my file with all the tables in it?

Thanks!

This script will help you:

<script type="text/javascript">
      function createDatabase(){
         try{
              if(window.openDatabase){
              var shortName = 'db_xyz';
              var version = '1.0';
              var displayName = 'Display Information';
              var maxSize = 65536; // in bytes
              db = openDatabase(shortName, version, displayName, maxSize);
        }
     }catch(e){
                 alert(e);
           }
     }
     function executeQuery($query,callback){
     try{
         if(window.openDatabase){
         db.transaction(
         function(tx){
         tx.executeSql($query,[],function(tx,result){
         if(typeof(callback) == "function"){
                 callback(result);
         }else{
                 if(callback != undefined){
                       eval(callback+"(result)");
                  }
         }
         },function(tx,error){});
          });
           return rslt;
         }
         }catch(e){}
         }
           function createTable(){
           var sql = 'drop table image';
                 executeQuery(sql);
                 var sqlC = 'CREATE TABLE image (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, image BLOB )';
                 executeQuery(sqlC);
           }
           function insertValue(){
                var img = document.getElementById('image');
                var sql = 'insert into image (name,image) VALUES ("sujeet","'+img+'")';
                executeQuery(sql,function(results){alert(results)});
            }
<input type="button" name='create' onClick="createDatabase()" value='Create Database'>
<input type="button" name='create' onClick="createTable()" value='create table'>
<input type="button" name='insert' onClick="insertValue()" value='Insert value'>
<input type="button" name='select' onClick="showTable()" value='show table'>
<input type="file" id="image" >
<div result></div>
</script>

To download the code go visit url:

http://blog.developeronhire.com/create-sqlite-table-insert-into-sqlite-table/

In my sqlite code I am using three js file for controlling sqlite one for debugging purpose, one for executing querys and another one for initilize the database and create basic tables.

debug.js
startup.js
query.js

Reference URL ishttp://allinworld99.blogspot.in/2016/04/sqlite-first-setup.html
startup.js

var CreateTb1 = "CREATE TABLE IF NOT EXISTS tbl1(ID INTEGER PRIMARY KEY AUTOINCREMENT, CreatedDate TEXT,LastModifiedDate TEXT, Name TEXT)";
var CreateTb2 = "CREATE TABLE IF NOT EXISTS tbl2(ID INTEGER PRIMARY KEY AUTOINCREMENT, CreatedDate TEXT,LastModifiedDate TEXT,Mark INTEGER)";

var DefaultInsert = "INSERT INTO tbl1(CreatedDate,Name) select '" + new Date() + "','Merbin Joe'  WHERE NOT EXISTS(select * from tbl1)";

var db = openDatabase("TestDB", "1.0", "Testing Purpose", 200000); // Open SQLite Database

$(window).load(function()
{
  initDatabase();
});

function createTable() // Function for Create Table in SQLite.
{

  db.transaction(function(tx)
  {
    tx.executeSql(CreateTb1, [], tblonsucc, tblonError);
    tx.executeSql(CreateTb2, [], tblonsucc, tblonError);

    insertquery(DefaultSettingInsert, defaultsuccess);

  }, tranonError, tranonSucc);
}

function initDatabase() // Function Call When Page is ready.
{
  try
  {
    if (!window.openDatabase) // Check browser is supported SQLite or not.
    {
      alert('Databases are not supported in your device');
    }
    else
    {
      createTable(); // If supported then call Function for create table in SQLite
    }
  }
  catch (e)
  {
    if (e == 2)
    {
      // Version number mismatch.
      console.log("Invalid database version.");
    }
    else
    {
      console.log("Unknown error " + e + ".");
    }
    return;
  }
}

debug.js

function tblonsucc()
{
  console.info("Your table created successfully");
}

function tblonError()
{
  console.error("Error while creating the tables");
}

function tranonError(err)
{
  console.error("Error processing SQL: " + err.code);
}

function tranonSucc()
{
  console.info("Transaction Success");
}

query.js

function insertquery(query, succ_fun)
{
  db.transaction(function(tx)
  {
    tx.executeSql(query, [], eval(succ_fun), insertonError);
  });
}

function deletedata(query, succ_fun)
{
  db.transaction(function(tx)
  {
    tx.executeSql(query, [], eval(succ_fun), deleteonError);
  });
}

function updatedata(query, succ_fun)
{
  db.transaction(function(tx)
  {
    tx.executeSql(query, [], eval(succ_fun), updateonError);
  });
}

function selectitems(query, succ_fun) // Function For Retrive data from Database Display records as list
{
  db.transaction(function(tx)
  {
    tx.executeSql(query, [], function(tx, result)
    {
      eval(succ_fun)(result.rows);
    });
  });
}

myDatabase and myDatabase.sqlite are 2 different filenames, update your code to reference the correct filename with extension.

SQLite does automatically create a new empty database if you try to open a database that doesn't exist.

I had same problem and I found out that you cannot use your sqlite db like this.

I used chrome and I found out that Chrome stores DBs in "C:\\Users\\%USERNAME%\\AppData\\Local\\Google\\Chrome\\User Data\\Default\\databases" .

There is a Databases.db that Chrome uses for managing DBs.

If you want to use your db you should add a record into Databases.db and put your file in "file__0" directory and rename it (your db file) to the id that is assigned to that record.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM