Error processing SQL:0 PhoneGap SQL - javascript

Im trying out and copied code from here:
http://luthfihariz.wordpress.com/2011/10/23/android-sqlite-phonegap-jquerymobile/
To succeed with a sample I'm working on just to learn this.
I have a link to my complete index.html on pastebin.
Please, correct me and also help me finding this errror.
Link to Pastebin here

I didn't have a lot of time, and it's soon xmas :) But.. :) I did write you a working example with your code as a starter.
Using Cordova version 2.2.0
Using PhoneGap to compile
I did test it on an android device
I did change some things here and there, but I used the code frome here as a reference.
document.addEventListener("deviceready", onDeviceReady, false);
var db = "";
function populateDB(tx) {
tx.executeSql('DROP TABLE IF EXISTS SoccerPlayer');
tx.executeSql('CREATE TABLE IF NOT EXISTS SoccerPlayer (Name TEXT NOT NULL, Club TEXT NOT NULL)');
tx.executeSql('INSERT INTO SoccerPlayer(Name,Club) VALUES ("Alexandre Pato", "AC Milan")');
tx.executeSql('INSERT INTO SoccerPlayer(Name,Club) VALUES ("Van Persie", "Arsenal")');
}
function queryDB(tx) {
tx.executeSql('SELECT * FROM SoccerPlayer', [], querySuccess, errorCB);
}
function querySuccess(tx,result){
var playerlist = document.getElementById("SoccerPlayerList");
var players = "";
alert("The show is on");
var len = result.rows.length;
for (var i=0; i<len; i++){
alert(result.rows.item(i).Name + result.rows.item(i).Club);
players = players + '<li><p class="record">'+result.rows.item(i).Name+'</p><p class="small">Club '+result.rows.item(i).Club+'</p></li>';
}
playerlist.innerHTML = players;
$("#SoccerPlayerList").listview("refresh");
}
function errorCB(err) {
alert("Error processing SQL: "+err.code);
}
function successCB() {
db.transaction(queryDB, errorCB);
}
function onDeviceReady() {
db = window.openDatabase("Database", "1.0", "PhoneGap Demo", 200000);
db.transaction(populateDB, errorCB, successCB);
}

Related

How to create database in PhoneGap?

I am new in android PhoneGap.
<script type="text/javascript" charset="utf-8" src="js/cordova.js"></script>
<script type="text/javascript" charset="utf-8">
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
var db = window.openDatabase("raddyx", "1.0", "Cordova Demo", 200000);
db.transaction(populateDB, errorCB, successCB);
}
function populateDB(tx) {
tx.executeSql('DROP TABLE IF EXISTS DEMO');
tx.executeSql('CREATE TABLE IF NOT EXISTS DEMO (id unique, data)');
tx.executeSql('INSERT INTO DEMO (id, data) VALUES (1, "First row")');
}
function errorCB(tx, err) {
alert("Error processing SQL: "+err);
}
function successCB() {
alert("success!");
}
</script>
I am using above sample code. My database name raddyx. I am unable to create database. Can you please say me how to create raddyx database in PhoneGap?
Edit - When i run it in my mobile it says Unfortunately, APP_NAME_HERE has stopped. If i remove my connection code it works fine.
You can create a database with a function like:
function queryDB() {
var db = window.openDatabase("Database", "1.0", "Cordova login", 300000);
db.transaction(inputDb, errorCB);
}
After that, you call the function inputDb which looks like:
function inputeDb(db2) {
db2.executeSql('DROP TABLE IF EXISTS login');
db2.executeSql('CREATE TABLE IF NOT EXISTS login (id_Login INTEGER PRIMARY KEY AUTOINCREMENT, UserName VARCHAR(150) NULL, UserPassword VARCHAR(100) NULL, UserHash VARCHAR(50) NULL)');
db2.executeSql('INSERT INTO login (UserName, UserPassword) VALUES ("'+uname1+'", "'+upass1+'")');
db2.executeSql('DROP TABLE IF EXISTS MDataT');
db2.executeSql('CREATE TABLE IF NOT EXISTS MDataT (id_MData INTEGER PRIMARY KEY, MData INTEGER)');
db2.executeSql('INSERT INTO MDataT (id_MData, MData) VALUES ("1", "'+MData+'")');
//alert("Username and Password - Set in DB");
location.href="serverLogin.html";
}

Having an Error processing SQL:0 PhoneGap SQL

I created an android app using html5 and phonegap and
I have a problem in inserting data into database..
this is my code
document.addEventListener("deviceready", onDeviceReady(), false);
var db;
function onDeviceReady(){
db = window.openDatabase("Libsys", "2.0", "LibraryDB", 200000); //will create database Dummy_DB or open it
db.transaction(populateDB, errorCB, successCB);
}
function populateDB(tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS Borrowinfo(id INTEGER PRIMARY KEY AUTOINCREMENT, IDno TEXT NOT NULL, Name TEXT NOT NULL, course TEXT NOT NULL, author TEXT NOT NULL, title TEXT NOT NULL, date_start TEXT NOT NULL, date_return TEXT NOT NULL)');
}
function queryDB(tx){
tx.executeSql('SELECT * FROM Borrowinfo', [], querySuccess, errorCB);
}
function querySuccess(tx,results){
var len = results.rows.length;
for (var i = 0; i < len; i++) {
var row = results.rows.item(i);
$("#Lists").append("<li><a href='#'>"+row['Name']+" "+row['course']+"</a></li>");
}
$("#Lists").listview("refresh");
}
function SaveContacts(idno,fullname,course,author,title,dstart,dreturn){
//alert(""+idno+" "+fullname+"");
db.transaction(function(tx){
var idno = document.getElementById("idno").value;
var fullname = document.getElementById("names").value;
var course = document.getElementById("course").value;
var author = document.getElementById("author").value;
var title = document.getElementById("title").value;
var dstart = document.getElementById("dstart").value;
var dreturn = document.getElementById("dreturn").value;
tx.executeSql('INSERT INTO Borrowinfo(IDno,name,course,author,title,date_start,date_return) VALUES (?,?,?,?,?,?,?)', [idno,fullname,course,author,title,dstart,dreturn], querySuccess);
alert("Record Save!");
});
}
function errorCB(err) {
alert("Error processing SQL: "+err.code);
}
function successCB() {
db.transaction(queryDB,errorCB);
}
im having an error in the function querySuccess.. the error message is (undefined is not a function querySuccess)
Please, correct me and also help me to fixed the error...
thank you..

user login using cordova

i'm gettin sql processing error sql:underfined here.Here i'm check whether the login form matched with the database called student and if there is a matched then an alert popup with welcome message and transfer to the next page.How do i fix the code?
document.addEventListener("deviceready", onDeviceReady, false);
var db;
function onDeviceReady() {
db = window.openDatabase("Database", "1.0", "Student",2*1024*1024);
db.transaction(createDB, errorCB, successCB);
}
function loginForm(){
db.transaction(checkDB, errorCB);
$.mobile.changePage("#page5",{reverse:false,transition:"slide"});
return false;
}
function checkDB(tx){
var _matric=$("[name='matric']").val();
var _password=$("[name='password']").val();
var sql ='select * from STUDENT where matric='+_matric+' and password='+_password+'';
tx.executeSql(sql,[],successLoginDB,errorCB);
}
function successLoginDB(tx,results){
var len = results.rows.length;
var _name =$("[name='name']").val();
if (len==1) {alert("Welcome "+_name);}
}
First you code is vulnerable to SQL Injection, fix it using args:
function loginForm(){
db.transaction(checkDB, errorCB);
$.mobile.changePage("#page5",{reverse:false,transition:"slide"});
return false;
}
function checkDB(tx){
var matric=$("[name='matric']").val();
var password=$("[name='password']").val();
var sql ='select * from STUDENT where matric = ? and password = ?';
tx.executeSql(sql,[matric, password],successLoginDB,errorCB);
}
function successLoginDB(tx,results){
var len = results.rows.length;
var name =$("[name='name']").val();
if (len==1) {alert("Welcome "+name);}
}
About error; I'm sure you are trying to use webSQL before cordova loads. You need wait for "DOM Ready" (for read text inputs) and "deviceready" for access to WebSQL:
document.addEventListener("deviceready", onDeviceReady, false);
var onDeviceReady = function () {
// Start here.
}
Please, post more info.

Check if DB exists and dropping DB in SQLlite IOS

I'm currently using phonegap to create and ios app.
While getting familiar to the sql javascript interactions I seem to have created 10 versions of the same named database file.
I'm currently using the following creation code (from the phonegap wiki)
var mydb=false;
// initialise the database
initDB = function() {
try {
if (!window.openDatabase) {
alert('not supported');
} else {
var shortName = 'phonegap';
var version = '1.0';
var displayName = 'PhoneGap Test Database';
var maxSize = 65536; // in bytes
mydb = openDatabase(shortName, version, displayName, maxSize);
}
} catch(e) {
// Error handling code goes here.
if (e == INVALID_STATE_ERR) {
// Version number mismatch.
alert("Invalid database version.");
} else {
alert("Unknown error "+e+".");
}
return;
}
}
// db error handler - prevents the rest of the transaction going ahead on failure
errorHandler = function (transaction, error) {
// returns true to rollback the transaction
return true;
}
// null db data handler
nullDataHandler = function (transaction, results) { }
my problem is that I'm unsure how to check if the database exists before creating it or how to create it only once per device?
and secondly how can i drop all these databases that have been created.
transaction.executeSql('DROP DATABASE phonegap;');
does not seem to drop anything.
Thanks
Please try following code. it is not creating multiple database files, just cross verify by visiting location -/Users/{username}/Library/Application Support/iPhone Simulator/4.3/Applications/{3D5CD3CC-C35B-41B3-BF99-F1E4B048FFFF}/Library/WebKit/Databases/file__0
This is sqlite3 example which cover create, insert, delete and drop queries on Table.
<!DOCTYPE html>
<html>
<body style="font: 75% Lucida Grande, Trebuchet MS">
<div id="content"></div>
<p id="log" style="color: gray"></p>
<script>
document.getElementById('content').innerHTML =
'<h4>Simple to do list</h4>'+
'<ul id="results"></ul><div>Handle Database in Phonegap</div>'+
'<button onclick="newRecord()">new record</button>'+
'<button onclick="createTable()">create table</button>' +
'<button onclick="dropTable()">drop table</button>';
var db;
var log = document.getElementById('log');
db = openDatabase("DBTest", "1.0", "HTML5 Database API example", 200000);
showRecords();
document.getElementById('results').addEventListener('click', function(e) { e.preventDefault(); }, false);
function onError(tx, error) {
log.innerHTML += '<p>' + error.message + '</p>';
}
// select all records and display them
function showRecords() {
document.getElementById('results').innerHTML = '';
db.transaction(function(tx) {
tx.executeSql("SELECT * FROM Table1Test", [], function(tx, result) {
for (var i = 0, item = null; i &lt result.rows.length; i++) {
item = result.rows.item(i);
document.getElementById('results').innerHTML +=
'<li><span contenteditable="true" onkeyup="updateRecord('+item['id']+', this)">'+
item['id']+' '+item['text'] + '</span> x</li>';
}
});
});
}
function createTable() {
db.transaction(function(tx) {
tx.executeSql("CREATE TABLE Table1Test (id REAL UNIQUE, text TEXT)", [],
function(tx) { log.innerHTML = 'Table1Test created' },
onError);
});
}
// add record with random values
function newRecord() {
var num = Math.round(Math.random() * 10000); // random data
db.transaction(function(tx) {
tx.executeSql("INSERT INTO Table1Test (id, text) VALUES (?, ?)", [num, 'Record:'],
function(tx, result) {
log.innerHTML = 'record added';
showRecords();
},
onError);
});
}
function updateRecord(id, textEl) {
db.transaction(function(tx) {
tx.executeSql("UPDATE Table1Test SET text = ? WHERE id = ?", [textEl.innerHTML, id], null, onError);
});
}
function deleteRecord(id) {
db.transaction(function(tx) {
tx.executeSql("DELETE FROM Table1Test WHERE id=?", [id],
function(tx, result) { showRecords() },
onError);
});
}
// delete table from db
function dropTable() {
db.transaction(function(tx) {
tx.executeSql("DROP TABLE Table1Test", [],
function(tx) { showRecords() },
onError);
});
}
</script>
</body>
</html>
And about Droping Database...
Does not seem meaningful for an embedded database engine like SQLite. To create a new database, just do sqlite_open(). To drop a database, simply delete the file.
thanks,
Mayur
Manually deleting the SQLite database from the Library worked for me. Thanks for the precious tip.

Phonegap-Android-sqlite using Javascript. How to connect?

I am new to Android-Phonegap dev. I am creating a project using Eclipse in Windows XP.
I am using sqlite database. I saw the sample code in the docs. But I'm not able to execute this example. I am not getting the required results.
Suppose I want to get all the entries in the table demo in tabular format, HTML. What will the code be in index.html? For that, what is the procedure and what is the step by step procedure for doing this? Or else any better tutorials which help me to do this?
Thanks in Advance
Dnyan.
in main.js you add this
rowsDataHandler = function(transaction, results) {
// Handle the results
var html = "<ul>";
for (var i=0; i<results.rows.length; i++) {
var row = results.rows.item(i);
html += '<li>'+row['data']+'</li>\n';
}
html +='</ul>';
document.getElementById("mydata").innerHTML = html;
}
// load the currently selected icons
loadRows = function(db) {
try {
db.executeSql('SELECT * FROM DEMO',[], rowsDataHandler, errorCB);
} catch(e) {alert(e.message);}
}
in index.html you add this row inside body
<div id="mydata"></div>
One thing to bear in mind is that if you aren't testing the application on a device or in an emulator, but rather in a browser like Chrome or Safari,
document.addEventListener("deviceready", onDeviceReady, false);
won't work. What I've done is to comment out this line and just to put in a call to
onDeviceReady();
When I then test in the emulator I uncomment the "document…" line and comment out
onDeviceReady();
**html**
<input id="show" type="button" value="Show">
**js**
function globalError(tx, error)
{
alert("Error: " + error.message);
}
var db = window.openDatabase('TabOrder', '', 'Bar Tab Orders', 2500000);
db.transaction(function(tx) {
tx.executeSql('DROP TABLE IF EXISTS SubmiteData;', null, null, globalError);
tx.executeSql('CREATE TABLE IF NOT EXISTS SubmiteData (SubmiteDataId integer
primary key, UserId text, AuthNo number, LocId number,ProdId number,
CardId number, OrgLat text, OrgLng text, OrgTime text)',
null,
function()
{
SubmiteData("USER1",12345678,23434, 21212, 220232,
"9", "45", "23/06/2014");
},
globalError);
});
function SubmiteData(UserId, AuthNo, LocId,ProdId, CardId, OrgLat, OrgLng, OrgTime){
db.transaction(function(tx){
tx.executeSql('INSERT INTO SubmiteData(UserId, AuthNo, LocId, ProdId, CardId,
OrgLat, OrgLng, OrgTime) VALUES (?,?,?,?,?,?,?,?)', [UserId, AuthNo, LocId,
ProdId, CardId, OrgLat, OrgLng, OrgTime],
null,
globalError
);
});
}
function read(UserId, AuthNo, LocId,ProdId, CardId, OrgLat, OrgLng, OrgTime){
db.transaction(function(tx) {
tx.executeSql('SELECT * FROM SubmiteData',
[],
function(tx, results)
{
for (var i=0; i<results.rows.length; i++)
{
var row=results.rows.item(i);
// alert("Id: " + row['UserId']);
var stringout = "LocId: " + row['LocId'] + "\n";
alert(stringout);
}
},
globalError
);
});
};
$(function()
{
$('#show').click(read);
});
this is the method to connect to a db using javascript
db = openDatabase("bprueba","1.0","Prueba_db",5*1023*1024);
SQL Statement Error Callback Reference

Categories

Resources