12

I'm using a PhoneGap project on Xcode. I am trying to connect to a SQLite database by using JavaScript.

I have made a file, "myDatabase.sqlite", in an SQLite tool. 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 that’s why it doesn't have any tables.

How can I open my file with all the tables in it?

4 Answers 4

11

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 this URL:

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

Sign up to request clarification or add additional context in comments.

4 Comments

This code drops the table with data you have already made in the sqlite file? So you still have to insert the data again in the code? All my data that i need is already in the SQLite file..
The link you've provided is dead, could you update it? Thanks
I tried using this code. I am using cordova to build this as an application in iPhone. But I am getting err.code 5. Can you please help me? @Sujeet
The HTML does not seem to be well-formed (indicated by the weird syntax highlighting).
1

In my SQLite code, I am using three JavaScript files for controlling SQLite, one for debugging purpose, one for executing queries, and another one for initializing the database and create basic tables.

debug.js
startup.js
query.js

The reference URL is http://allinworld99.blogspot.in/2016/04/sqlite-first-setup.html

File 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 the 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 the function
                     // for creating a table in SQLite
    }
  }
  catch (e)
  {
    if (e == 2)
    {
      // Version number mismatch
      console.log("Invalid database version.");
    }
    else
    {
      console.log("Unknown error " + e + ".");
    }
    return;
  }
}

File 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");
}

File 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 retrieving data
                                      // from the database. Display
                                      // records as list
{
  db.transaction(function(tx)
  {
    tx.executeSql(query, [], function(tx, result)
    {
      eval(succ_fun)(result.rows);
    });
  });
}

Comments

1

myDatabase and myDatabase.sqlite are two different filenames. Update your code to reference the correct filename with an extension.

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

1 Comment

When I use the name myDatabase.sqlite the program stops at the openDatabase command (I have put an alert before and after that line... and it shows the first alert, but not the second. So thats why I was thinking that that is problem... Got any idea's?
0

I had the same problem, and I found out that you cannot use your SQLite database like this.

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

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.