最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

SQLite database in Javascript locally - Stack Overflow

programmeradmin1浏览0评论

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!

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!

Share Improve this question edited Jul 24, 2015 at 7:48 danopz 3,4085 gold badges33 silver badges43 bronze badges asked Mar 9, 2011 at 10:33 TjekklesTjekkles 5,6128 gold badges37 silver badges53 bronze badges
Add a comment  | 

4 Answers 4

Reset to default 12

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/

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.

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 is http://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);
    });
  });
}

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.

发布评论

评论列表(0)

  1. 暂无评论