Issue with insert and select multiple rows in Sqlite using phonegap - javascript

I am new to Sqlite and java script. I am getting struck with inserting and selecting multiple rows in sqlite database. Can any one help me to that how can I insert and select multiple rows ? my code is as follows,
var db = window.sqlitePlugin.openDatabase("Database", "1.0", "Demo", -1);
db.transaction(function(tx) {
tx.executeSql('DROP TABLE IF EXISTS test_table');
tx.executeSql('CREATE TABLE IF NOT EXISTS test_table (id integer primary key, data text, data_num integer)');
tx.executeSql("INSERT INTO test_table (data, data_num) VALUES (?,?)", ["test", 100], function(tx, res) {
console.log("insertId: " + res.insertId + " -- probably 1"); // check #18/#38 is fixed
alert("insertId: " + res.insertId + " -- should be valid");
db.transaction(function(tx) {
tx.executeSql("SELECT data_num from test_table;", [], function(tx, res) {
console.log("res.rows.length: " + res.rows.length + " -- should be 1");
alert("res.rows.item(0).data_num: " + res.rows.item(i).data_num + " -- should be 100");
});
});
}, function(e) {
console.log("ERROR: " + e.message);
});
});
And How can i insert values from one java script function and how can i retrieve values from another function is it possible? if yes can anyone suggest some good tutorials or explain the same.

Related

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?

Use Database with Phonegap application

This can't be a proper question to ask here, but I am a bit confused about How & which database to use with my phonegap application (made with HTML5 + Javascript+CSS)
If anyone having any Reference link or any Idea of'
How I can use database in this application?
Thanks in advance.
You can use SQLite wrapper.
Plugin Link
It's very easy to use.
// Wait for Cordova to load
document.addEventListener("deviceready", onDeviceReady, false);
// Cordova is ready
function onDeviceReady() {
var db = window.sqlitePlugin.openDatabase({name: "my.db"});
db.transaction(function(tx) {
tx.executeSql('DROP TABLE IF EXISTS test_table');
tx.executeSql('CREATE TABLE IF NOT EXISTS test_table (id integer primary key, data text, data_num integer)');
// demonstrate PRAGMA:
db.executeSql("pragma table_info (test_table);", [], function(res) {
console.log("PRAGMA res: " + JSON.stringify(res));
});
tx.executeSql("INSERT INTO test_table (data, data_num) VALUES (?,?)", ["test", 100], function(tx, res) {
console.log("insertId: " + res.insertId + " -- probably 1");
console.log("rowsAffected: " + res.rowsAffected + " -- should be 1");
db.transaction(function(tx) {
tx.executeSql("select count(id) as cnt from test_table;", [], function(tx, res) {
console.log("res.rows.length: " + res.rows.length + " -- should be 1");
console.log("res.rows.item(0).cnt: " + res.rows.item(0).cnt + " -- should be 1");
});
});
}, function(e) {
console.log("ERROR: " + e.message);
});
});
}
Detailed documentation available in the link.
If you need small data to save like few words, then you can use localStorage.

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.

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