SQLite database in Javascript locally - javascript

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/

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.

Related

I get "new transaction is queued, waiting for open operation to finish" when I use cordova SQLite

I just started learning SQLite and I use only cordova without Ionic and I am trying to understand why I get the console return: "new transaction is queued, waiting for open operation to finish" when I try to do something with the database
$(document).ready(function(){
var myDB;
//Open Database Connection
document.addEventListener("deviceready",onDeviceReady,false);
function onDeviceReady(){
myDB = window.sqlitePlugin.openDatabase({name: "mySQLite.db", location: 'default'});
}
//Create new table
$("#createTable").click(function(){
myDB.transaction(function(transaction) {
transaction.executeSql('CREATE TABLE IF NOT EXISTS phonegap_pro (id integer primary key, title text, desc text)', [],
function(tx, result) {
alert("Table created successfully");
},
function(error) {
alert("Error occurred while creating the table.");
});
});
});
//Insert New Data
$("#insert").click(function(){
var title="Hello";
var desc="World";
console.log(title +""+ desc);
myDB.transaction(function(transaction) {
var executeQuery = "INSERT INTO phonegap_pro (title, desc) VALUES (?,?)";
transaction.executeSql(executeQuery, [title,desc]
, function(tx, result) {
alert('Inserted');
},
function(error){
alert('Error occurred');
});
});
});
//Display Table Data
$("#showTable").click(function(){
$("#TableData").html("");
myDB.transaction(function(transaction) {
transaction.executeSql('SELECT * FROM phonegap_pro', [], function (tx, results) {
var len = results.rows.length, i;
$("#rowCount").html(len);
for (i = 0; i < len; i++){
$("#TableData").append("<tr><td>"+results.rows.item(i).id+"</td><td>"+results.rows.item(i).title+"</td><td>"+results.rows.item(i).desc+"</td><td><a href='edit.html?id="+results.rows.item(i).id+"&title="+results.rows.item(i).title+"&desc="+results.rows.item(i).desc+"'>Edit</a> <a class='delete' href='#' id='"+results.rows.item(i).id+"'>Delete</a></td></tr>");
}
}, null);
});
});
});
The problem was that I was testing it in the browser

Database and local Storage get cleared in IOS phonegap application

About App -
I am using corodova 2.1.0 in ios phonegap application.
My app does some registration process in that it checks if the app is registered or not if it found data in database or local storage it goes to dashboard else it ask for registration.
In registration process app ask for mobile no if mobile entry from back end is fond then app will download data from database and stores it in localstorage and database.
Issue-
if is give registered for first time app downloads data and goes to dashboard. and if i kill the app and then open it it will ask for registration and if i registered second time and after going on dashboard if i kill app and open again app then it will shows dasboard afterwords it donesn't show registration screen.
I checked on weinre first time also it loads all data in database and local sotrage.
i am storing only name and user's id. but it get cleared if i kill app after first installation.
//Here is code which checks that user is registred or not
// this will ckeck on splashscrenn
//$window.location.href = '#/SplashScreen';
function checkregistration(){
var sqlU = 'SELECT ClubId, MemberId, MemberName FROM member_master_dtls';
var obj = {};
var db = window.openDatabase("ROW_DB", "", "Cordova Demo", 200000);
try{
var MID = localStorage.getItem('MyMemberID');
console.log("MID befo "+ typeof(MID));
console.log("MID === "+ (MID));
if ( MID.length>0)
{
console.log("MID"+ MID);
RowDbService.CheckVersion();
$window.location.href = '#/Dashboard';
}else{
db.transaction(function(tx) {
//console.log('in db trans');
tx.executeSql(sqlU, [], SuccessChkMemlst_local, errorCB);
});
}
}
catch(err){
db.transaction(function(tx) {
//console.log('in db trans');
tx.executeSql(sqlU, [], SuccessChkMemlst_local, errorCB);
});
}
}
function SuccessChkMemlst_local(tx, results) {
//alert("success splash");
//console.log("successlist = " + results.rows.length);
if (results.rows.length == 0) {
//localStorage.setItem('globalx', '1');
globalx = 1;
$window.location.href = '#/Register';
//console.log(results);
} else {
RowDbService.CheckVersion();
$window.location.href = '#/Dashboard';
}
}
=================================
//here is function on Register page that download data from webservice and store it in database
//$window.location.href = '#/Register';
function ChkForRegistration(){
//here some webservices wich downloads th
localStorage.setItem('ClubID', obj[0].ClubId);
localStorage.setItem('MyMemberName', obj[0].member_name);
localStorage.setItem('MyMemberID', obj[0].member_master_id);
localStorage.setItem('MyClubName', obj[0].club_name);
localStorage.setItem('NewsCount',0);
localStorage.setItem('AnnCount',0);
localStorage.setItem('EventCount',0);
localStorage.setItem('BdayCount',0);
localStorage.setItem('EventDate',"");
localStorage.setItem('BdayDate',"");
var datarow = {};
datarow.MemberId = localStorage.getItem('MyMemberID');
datarow.MemberName = localStorage.getItem('MyMemberName');
datarow.ClubId = localStorage.getItem('ClubID');
datarow.ClsfyName = localStorage.getItem('MyClubName');
var db = window.openDatabase("ROW_DB", "", "Cordova Demo", 200000);
db.transaction(function(tx) {
var query="insert into member_master_dtls (id,MemberId,MemberName,ClubId,ClsfyName) values(?,?,?,?,?)";
tx.executeSql("update sqlite_sequence set seq = 0 where name ='member_master_dtls'");
tx.executeSql("delete from member_master_dtls");
tx.executeSql(query,[(1),datarow.MemberId,datarow.MemberName,datarow.ClubId,datarow.ClsfyName]);
tx.executeSql("update sqlite_sequence set seq =1 where name ='member_master_dtls'");
});
$window.location.href = '#/Dashboard';
}

Check a Boolean value from database at the start of an app then load terms and condition page if false, load menu page if true

Is this possible?
Before any page loads, could I run JavaScript code to check what the value in a database is, then open the relevant page?
Here is my code so far:
function onDeviceReady() //Phone gap is ready
{
try
{
db = openDatabase('cuopioid', '1.0', 'cupioids application database',
2 * 1024 * 1024);
} catch (e)
{
// Error handling code goes here.
if (e == INVALID_STATE_ERR)
{
// Version number mismatch.
alert("Invalid database version.");
}
else
{
alert("Unknown error " + e + ".");
}
}
console.log("DATABASE Created!");
db.transaction(createTableTerms, errCB, console.log("MEDICINES Table Created!"));
$('#btnaccept').on('click', acceptTerms);
}
The code below creates the database (if it isn't there already)
function createTableTerms(tx)
{
tx.executeSql('CREATE TABLE IF NOT EXISTS TERMS (id unique, status boolean)');
tx.executeSql('INSERT INTO TERMS (id, status) VALUES (0, 0)');
console.log("TERMS Table Created!");
}
I have created this function which selects the rows form the database if it is set to true, then if the results has 1 record I want it to open the menu page, if it has no results it means the terms and conditions haven't been accepted previously:
function checkTerms(tx)
{
db.transaction(function(tx)
{
tx.executeSql('SELECT * FROM TERMS WHERE status=1', [],console.log("check terms"), errCB);
});
var len = results.rows.length;
if (len = 1)
{
console.log("accepted previously - menu page");
}
else
{
console.log("termsandconditions page");
}
}
I am not sure where to put this checkTerms(tx) function
I solved this problem by creating a new JavaScript file which runs when a html page lodes (start of the <head> tag
Which opens the database
Runs the SQL query to find the value
Opens the relevant page depending on the result
It still displays the page (half a second at most) when I load the page, but it does what I want
Here is the code:
try
{
db = openDatabase('cuopioid', '1.0', 'cupioids application database',
2 * 1024 * 1024);
} catch (e)
{
// Error handling code goes here.
if (e == INVALID_STATE_ERR)
{
// Version number mismatch.
alert("Invalid database version.");
}
else
{
alert("Unknown error " + e + ".");
}
}
checkTerms();
function checkTerms(tx)
{
db.transaction(function(tx)
{
tx.executeSql('SELECT * FROM TERMS WHERE status=1', [], openPage, errCB);
});
}
function openPage(tx, results)
{
var len = results.rows.length;
if (len = 1)
{
getDrugs();
window.location.href = "#page1"
console.log("accepted previously - menu page");
}
else
{
window.location.href = "#page0"
console.log("termsandconditions page");
}
}
Another way to solve this may of been to write a php page as kind of a clearing house based on your database values, then redirect the user to the relevent page. You could do this with ajax and the user wouldn't momentarily see the wrong page either.

openDatabase stuck

I have a project with Blackberry Web Work, and this is my first time for mobile programming.
I want to create cache database using window.openDatabase
But something is strange, I put alert after to show this database, but it didnot show anything.
I also put alert before and after this function, only show alert before this function
I try to put try catch error, but it still not show error message.
Need your help
Thx
Here is my simple code :
$(document).ready(function() {
try {
if (!window.openDatabase) {
alert('not supported');
} else {
var shortName = 'mydatabase';
var version = '1.0';
var displayName = 'My Important Database';
var maxSize = 65536; // in bytes
alert("prepare to open database");
var db = openDatabase(shortName, version, displayName, maxSize);
alert("open Database");
// You should have a database instance in db.
}
} catch (e) {
// Error handling code goes here.
if (e == 2) {
// Version number mismatch.
alert("Invalid database version.");
} else {
alert("Unknown error " + e + ".");
}
return;
}
alert("Database is: " + db);
});​
Your issue seems to be related to the positioning of your try/catch statements. I rearranged your sample code and it is working:
$(document).ready(function () {
if (!window.openDatabase) {
alert('not supported');
} else {
try {
var shortName = 'mydatabase';
var version = '1.0';
var displayName = 'My Important Database';
var maxSize = 65536; // in bytes
alert("prepare to open database");
var db = openDatabase(shortName, version, displayName, maxSize);
alert("open Database");
// You should have a database instance in db.
} catch (e) {
// Error handling code goes here.
if (e == 2) {
// Version number mismatch.
alert("Invalid database version.");
} else {
alert("Unknown error: " + e + ".");
}
return;
}
alert("Database is: " + db);
}
});
Keep in mind that openDatabase is not supported on all browsers. FireFox and IE will give you the 'not supported' alert, and Chrome and Safari will display the remaining alerts.
Here is the JSFIDDLE link to test the modified code http://jsfiddle.net/sdarya/0pkvLfpv/

HTML5, SQLite transaction question

In my HTML5, i have a for loop which calls a function to insert into a database. I need this function to be inside a single transaction.
function Ins(id){
db.transaction(function(tx){
tx.executeSql('insert into Product(id) values(?);', [iName], function() {}, function() { });
});
}
The for loop
db.transaction(function(tx){tx.executeSql("BEGIN",[]);});
for (intCountLine=1;intCountLine<=1000;intCountLine++)
{
Ins(intCount);
}
db.transaction(function(tx){tx.executeSql("COMMIT",[]);});
You can see, i have the transaction begin & commit, but i assume when it calls the INS function, it would open a new transaction and close it, everytime it is called. How do i make sure that doesn't happen.
googled it but could not find it... throw me some light here....
May be this will works. Use insert select union all instead of creating 1000 insert statements. But this can insert only 500 rows at a time. Here is the code which i worked on, do a test on Google chrome i am sure it works.
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
var db = openDatabase('mydb', '1.0', 'Test DB', 2 * 1024 * 1024);
var msg;
var j=1;
var i=1;
var quer="";
db.transaction(function(tx){tx.executeSql("CREATE TABLE IF NOT EXISTS LOGS (ID INTEGER PRIMARY KEY ASC, todo TEXT)",[]);});
db.transaction(function(tx){tx.executeSql("delete from logs",[]);});
txquer();
showMsg();
function txquer()
{
quer="insert into logs ";
for(i=j;i<=j+498;i++)
{
quer+=" select "+i+",'test' union all";
}
quer+=" select "+i+",'test' ; ";
j=i+1;
db.transaction(
function(tx){
tx.executeSql(quer,[]);
}
);
}
function showMsg(){
db.transaction(function (tx) {
tx.executeSql('SELECT count(*) todo FROM LOGS', [], function (tx, results) {
var len = results.rows.item(0).todo;
msg = "<p>Found rows: " + len + "</p>";
document.querySelector('#status').innerHTML += msg;
}, null);
});
}

Categories