HTML5, SQLite transaction question - javascript

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

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

SQLite plugin Cordova basic code

I'm new to Cordova & Sqlite but I wrote some code and I can't figure out what is wrong with it? Any suggestions?
I always get the following output from the Javascript debugger:
Click to see error messages
<script type="text/javascript">
// Wait for Cordova to load
document.addEventListener('deviceready', onDeviceReady, false);
var output = document.getElementById('outputField');
// Cordova is ready
function onDeviceReady() {
window.sqlitePlugin.openDatabase({ name: 'test.db', location: 2 }, function (db) {
output.innerHTML += '</br> - Database created/opened';
db.transaction(function (tx) {
tx.executeSql(tx, "CREATE TABLE localStorage2 IF NOT EXISTS (key UNIQUE, value)");
});
output.innerHTML += '</br> - Table localStorage2 Created';
storeValue(db, 'localStorage2', 'testKey', 'testValue');
output.innerHTML += '</br> - Insert dummy value';
output.innerHTML += '</br> ' + readValue(db, 'localStorage2', 'testKey');
});
}
function storeValue(db, table, key, value) {
db.transaction(function (tx) {
tx.executeSql(tx, 'INSERT INTO ' + table + ' (key,value) VALUES ("' + key + '","' + value + '")');
});
}
function readValue(db, table, key) {
db.transaction(function (tx) {
return db.executeSql(tx, 'SELECT * FROM ' + table + ' WHERE key="' + key + '"');
});
}
</script>
If you are testing a new plugin, library, … whatever, the best way is to read the docs, play a little bit with the examples and expand it step by step for your needs.
The SQLite plugin is event driven, that means, that you have to wait until the job is done.
You are doing it this way and this don't work:
var the_result = mySQL_Job();
function mySQL_Job(){
db.readTransaction(function(tx) {
return db.executeSql(…);
});
}
The right way is:
mySQL_Job();
function mySQL_Job(some_values){
tx.executeSql("SELECT * FROM myTable", [], function(tx, res) {
//Here goes your result handling, like inserting values in your html
}, function(error) {
console.log('SQLite error: ' + error.message);
});
}
This you have to do for every sql job, please see the docs at: https://github.com/litehelpers/Cordova-sqlite-storage
If you have a lot of queries then it is a good idea to use promises: How to compact SQL instructions in Cordova?

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.

Web SQL DROP/DELETE Table not working

I've tried several different commands for clearing my Web SQL Database and none of them work. Just to show you I've assembled all of them into one overkill function. What am I missing?
/** Drop Table from Database - Fix This **/
function overKill(tablename){
var query = "DELETE FROM " + tablename;
db.transaction(function (tx) {
tx.executeSql(query);
});
var query = "DELETE * FROM " + tablename;
db.transaction(function (tx) {
tx.executeSql(query);
});
var query = "DROP TABLE " + tablename;
db.transaction(function (tx) {
tx.executeSql(query);
});
}
This worked for me
tx.executeSql("DROP TABLE foo",[],
function(tx,results){console.log("Successfully Dropped")},
function(tx,error){console.log("Could not delete")}
);
Worked for me:
tx.executeSql('DELETE FROM FormRecords');
Moreover, you cannot delete a Web SQL database.
DELETE * FROM...
does not make sense. use DELETE FROM instead
You last variant is correct. Just for testing you can open your web resourse by Chrome. Then open Resourses -> Web SQL where you can type DROP TABLE TABLENAME and check if everething is right.
The follow code should works well:
var db = openDatabase(databaseName, "0.1", description, size)
var db.transaction(function (t) {
t.executeSql("DROP TABLE objectTable",[],
function(t,results){
console.error("Table Dropped")
},
function(t,error){
console.error("Error: " + error.message)
}
)
})

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/
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.

Categories