I am using PhoneGap and WebSql. When i am trying it on browser everything is fine.SQLResultSet object has 3 property which are rows,insertId and rowsAffected.
But When i generate and Apk and trying a mobile device, SQLResultSet object has two property rows and rowsAffected.It is getting rowsAffected 0 on mobile device however it is getting 1 in browser on pc.On mobile device 'insertID' getting undefined.
db.transaction(function (t) {
t.executeSql("INSERT INTO TEST (Testname) VALUES (?)", ["test"], function (t, rresult) {
alert(JSON.stringify(rresult));
}, function (t, error) {
alert(error)
})
}, function (error) {
alert("error" + error);
},
function (success) {
alert("success" + success);
})
thanks for help.
The table creation is below.
tx.executeSql("CREATE TABLE IF NOT EXISTS TESTT (Id INTEGER PRIMARY KEY,Testname text)", [],
function (tx, results) { console.log("Successfully created") },
function (tx, error) { console.log("Could not created") }
Related
Im about to build a Ionic Inventory Management app with Barcode Scanner and SQLite with the help of this tutorial: https://www.techiediaries.com/ionic-cordova-sqlite-barcode-scanner-product-inventory-manager/
When I add this code:
constructor(public sqlite :SQLite) {
console.log('Hello DataServiceProvider Provider')
this.sqlite.create({name: "data.db", location:
"default"}).then((db : SQLiteObject) => {
this.database = db;
}, (error) => {
console.log("ERROR: ", error);
});
...to data-service.service.ts I got this error:
core.js:19866 ERROR Error: Uncaught (in promise): TypeError: Cannot
read property 'then' of undefined TypeError: Cannot read property
'then' of undefined
at new DataServiceService (data-service.service.ts:64)
at _createClass (core.js:26976)
at createProviderInstance (core.js:26941)
at resolveNgModuleDep (core.js:26888)
at NgModuleRef.get (core.js:27996)
at resolveNgModuleDep (core.js:26908)
at NgModuleRef_.get (core.js:27996)
at resolveDep (core.js:28518)
at createClass (core.js:28366)
at createDirectiveInstance (core.js:28186)
at resolvePromise (zone.js:831)
at resolvePromise (zone.js:788)
at zone.js:892
at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask
(zone.js:423)
at Object.onInvokeTask (core.js:21826)
at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask
(zone.js:422)
at Zone.push../node_modules/zone.js/dist/zone.js.Zone.runTask (zone.js:195)
at drainMicroTaskQueue (zone.js:601)
This is the whole data-service.service.ts code:
import { Injectable } from '#angular/core';
import { SQLite, SQLiteObject } from '#ionic-native/sqlite/ngx';
#Injectable({
providedIn: 'root'
})
export class DataServiceService {
public database: SQLiteObject;
productTable : string = `CREATE TABLE IF NOT EXISTS products (
id INTEGER PRIMARY KEY,
sku TEXT,
barcode TEXT,
title TEXT NOT NULL,
description TEXT,
quantity REAL,
unit VARCHAR,
unitPrice REAL,
minQuantity INTEGER,
familly_id INTEGER,
location_id INTEGER,
FOREIGN KEY(familly_id) REFERENCES famillies(id),
FOREIGN KEY(location_id) REFERENCES locations(id)
);`;
familyTable : string = `CREATE TABLE IF NOT EXISTS famillies (
id INTEGER PRIMARY KEY,
reference VARCHAR(32) NOT NULL,
name TEXT NOT NULL,
unit VARCHAR);`;
locationTable : string = `CREATE TABLE IF NOT EXISTS locations (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL);`;
//Date , Quantity , Unit Cost , Reason (New Stock - Usable Return - Unusable Return ) ,UPC (Universal Product Code ) Comment
transactionTable : string = `CREATE TABLE IF NOT EXISTS transactions (
id INTEGER PRIMARY KEY,
date TEXT,
quantity REAL,
unitCost REAL,
reason VARCHAR,
upc TEXT,
comment TEXT,
product_id INTEGER,
FOREIGN KEY(product_id) REFERENCES products(id));`;
async createTables(){
try {
await this.database.executeSql(this.familyTable);
await this.database.executeSql(this.locationTable);
await this.database.executeSql(this.productTable);
await this.database.executeSql(this.transactionTable);
}catch(e){
console.log("Error !");
}
}
constructor(public sqlite :SQLite) {
console.log('Hello DataServiceProvider Provider')
this.sqlite.create({name: "data.db", location: "default"}).then((db : SQLiteObject) => {
this.database = db;
}, (error) => {
console.log("ERROR: ", error);
});
}
}
Does anyone has an idea how to fix it?
Your code won't work in browser when running ionic serve, because:
As per mentioned here
Cordova needs plugins to run in browser
And they are not added by default. So you can run the project with ionic cordova run browser
OR as mentioned in the comment as well, mock the plugin. Tried it and it worked:
in app module, mock the create:
import { SQLite , SQLiteDatabaseConfig , SQLiteObject } from '#ionic-native/sqlite';
class SQLiteMock {
public create(config: SQLiteDatabaseConfig): Promise<SQLiteObject> {
return new Promise((resolve,reject)=>{
resolve(new SQLiteObject(new Object()));
});
}
}
Mark it in providers like:
{provide: SQLite, useClass: SQLiteMock},
Create a file sql.js file in the folder and copy the content from here: https://raw.githubusercontent.com/kripken/sql.js/master/js/sql.js
and add to your index.html:
<script src="assets/sql.js"></script>
<script src="build/polyfills.js"></script>
<script src="build/main.js"></script>
Now your function should work just fine. Going the further steps, I suggest you follow the link I provided before this code, i.e: https://www.techiediaries.com/mocking-native-sqlite-plugin/
One thing you could look into is whether the constructor is being run before the async function in your code. If so look into implementing something along the lines on ngOnInit.
I am running Ionic 2 RC4 and when I run ionic run android the app works, but device ready is firing after 15-18 seconds. I tried to run on device ionic run android --prod, but it shows in chrome inspector that sqlite plugin is not installed which is not true. If I go to another page and come back it shows my data from SQLite.
constructor is called
main.js:1 Native: tried accessing the SQLite plugin but it's not installed.
x # main.js:1
main.js:1 Install the SQLite plugin: 'ionic plugin add cordova-sqlite-storage'
x # main.js:1
cordova.js:1223 deviceready has not fired after 5 seconds.
cordova.js:1216 Channel not fired: onFileSystemPathsReady
main.js:4 Native: deviceready did not fire within 2000ms. This can happen when plugins are in an inconsistent state. Try removing plugins from plugins/ and reinstalling them.
(anonymous) # main.js:4
main.js:4 DEVICE READY FIRED AFTER 2684 ms
error getting scheduled matches TypeError: Cannot read property 'executeSql' of undefined
at _ (main.js:1)
at main.js:1
at main.js:1
at new t (polyfills.js:3)
at e (main.js:1)
at s (main.js:1)
at t.<anonymous> (main.js:1)
at t.value [as executeSql] (main.js:1)
at t.getScheduledMatches (main.js:9)
at t.getMatchInfo (main.js:23)
I tried to place device ready in several different locations and I also logged in many places. The last console log that is called is called constructor
constructor(public timeSince: TimeSinceService,
public platform: Platform) {
console.log("constructor is called"); //called
if(!this.isOpen){
this.db = new SQLite();
this.db.openDatabase({name: "aces.db", location: "default"}).then(() => {
console.log("open Database"); // not called
this.db.executeSql('PRAGMA user_version = 0', []).then(()=>console.log("yesss")) // not called
this.db.executeSql('PRAGMA user_version', []).then(data => {
if(data.rows.item(0).user_version !== current_version){
console.log("versions do not match");
}
})
this.db.executeSql('PRAGMA foreign_keys = ON', []).then(()=>{
let query_matches = 'CREATE TABLE IF NOT EXISTS matches '+
'(id INTEGER PRIMARY KEY AUTOINCREMENT,'+
...';
let query_comments = 'CREATE TABLE IF NOT EXISTS comments '+
'(id INTEGER PRIMARY KEY AUTOINCREMENT, '+
...';
let query_points = 'CREATE TABLE IF NOT EXISTS undo'+
'(point_id INTEGER PRIMARY KEY AUTOINCREMENT,'+
...';
let query_organizations = 'CREATE TABLE IF NOT EXISTS organizations '...
let query_users = 'CREATE TABLE IF NOT EXISTS users '+
'(id INTEGER PRIMARY KEY AUTOINCREMENT,'+
...';
Promise.all([
this.db.executeSql(query_matches, {}).then(() => {
console.log("table created");
}, (err) => console.error('Unable to execute sql for matches: ', err)),
this.db.executeSql(query_comments, {}).then(() => {
console.log("comment table created");
}, (err) => console.error('Unable to execute sql for create comment table: ', err)),
this.db.executeSql(query_organizations, {}).then(() => {
console.log("table organizations created");
}, (err) => console.error('Unable to execute sql: ', err)),
this.db.executeSql(query_points, {}).then(() => {
console.log("undo table created");
}, (err) => console.error('Unable to execute sql for undo table: ', err)),
this.db.executeSql(query_users, {}).then(() => {
console.log("table users created");
}, (err) => console.error('Unable to execute sql: ', err))
]).then(()=> {
console.log("called promise all");
this.isOpen = true
})
})
}, (error) => console.log("ERROR couldn't open database from sqlite service: ", error));
}
}
Answering my own question in case somebody runs into the same problem.
I had to call rootPage inside DeviceReady inside my app.component.ts. I hope it helps to somebody.
I am not getting what's happening with my codes. I don't know why I am getting No. of '?'s in statement string doesn't match arguement count while I am not using '?' to insert values. Here is my code:
db = window.openDatabase("myDB", "1.0", "Test DB", 2000000);
db.transaction(populateDB, errorCB, successCB);
$.ajax({
type: 'POST',
url: "MY_SERVER_URL",
data: {"email": email, "password": password},
success: function (response) {
db.transaction(function (tx) { saveDetailsInDB(tx, JSON.stringify(response)) } ,errorCB , successInsertion);
},
error: function (errorMessage) {
window.alert("Something went wrong!");
}
});
}
}
function populateDB(tx) {
tx.executeSql('DROP TABLE IF EXISTS UserDetailsInJSONform');
tx.executeSql('CREATE TABLE IF NOT EXISTS UserDetailsInJSONform (ID INTEGER, JSONdetails TEXT)');
tx.executeSql('INSERT INTO UserDetailsInJSONform (ID,JSONdetails) VALUES (1,"asd")');
}
function saveDetailsInDB(tx, response){
tx.executeSql('INSERT INTO UserDetailsInJSONform (ID,JSONdetails) VALUES (1,"asd")',done,errorCB);
}
function done(tx) {
alert("success ");
tx.executeSql('SELECT * FROM UserDetailsInJSONform', [], querySuccess, errorCB);
}
// Transaction error callback
function errorCB(err) {
alert("Error processing SQL: "+err.code+" "+err.message);
}
// Transaction success callback
function successCB() {
alert("Positive successCB");
}
function successInsertion() {
alert("Positive successInsertion");
}
function querySuccess(tx,results){
var len = results.rows.length;
alert("Row no. "+len);
for (var i=0; i<len; i++){
alert(results.rows.item(i).ID);
alert(results.rows.item(i).JSONdetails );
}
}
I am beginner in Phonegap. I tried to save my returned data from server in local SQLite DB. But I don't know why I am getting unknown errors. Please Help me !!
2nd argument in tx.executeSql expects values between brackets.
tx.executeSql(sqlToExecuteForTx,bracketValuesForTx,success,error);
In your code:
tx.executeSql('INSERT INTO UserDetailsInJSONform (ID,JSONdetails) VALUES (1,"asd")',done,errorCB);
It has 'done' as second value which refers to a function in your code. I would recommand to use:
tx.executeSql('INSERT INTO UserDetailsInJSONform (ID,JSONdetails) VALUES (?,?)',[1,"asd"],done,errorCB);
I am working with intel XDK and there I have a prepopulated .db file which i need to read inside my code. As we do in native app where we put db files in assets directory and then access those database by copying them in app's database directory. I am new to hybrid apps.
NB: For view DB created by your project ,
1st take a windows build and run your project .
Then go to
C:\Users\XXXXX\AppData\Local\Packages\pakagename\LocalState\yourdbname.db
You can find your DB file
you can view that file on this site
For database creation and usage
Please use the link to the Intel XDK third party plugin. Before that please download the project dependency jar file from GitHub and create the directory with Cordova plugin SQLite name and place the file in it, include the jar file. Then try to add the plugin using URL .
See the whole code below
1.create database
2.add table
3.add data to table
4.get data from table
> // Wait for Cordova to load
document.addEventListener('deviceready', onDeviceReady, false);
// Cordova is ready
function onDeviceReady() {
////////////////////////////////////////////////////////////////////////////////////////////////
alert("Start ");
var db = window.sqlitePlugin.openDatabase({ name: 'my.db', location: 'default' }, function () {
alert("database creatred");
db.transaction(function (tx) {
tx.executeSql('CREATE TABLE customerAccounts (firstname, lastname, acctNo)');
alert("Table create");
addItem("first", "last", 100);
getData("last");
}, function (error) {
alert('transaction error: ' + error.message);
}, function () {
alert('transaction ok');
});
}, function (error) {
});
////////////////////////////////////////////////////////////////////////////////////////////////
function addItem(first, last, acctNum) {
alert("start adding");
db.transaction(function (tx) {
var query = "INSERT INTO customerAccounts (firstname, lastname, acctNo) VALUES (?,?,?)";
alert("start insterting");
tx.executeSql(query, [first, last, acctNum], function(tx, res) {
console.log("insertId: " + res.insertId + " -- probably 1");
console.log("rowsAffected: " + res.rowsAffected + " -- should be 1");
alert("insert complete");
},
function(tx, error) {
alert('INSERT error: ' + error.message);
});
}, function(error) {
alert('transaction error: ' + error.message);
}, function() {
alert('transaction ok');
});
}
////////////////////////////////////////////////////////////////////////////////////////////////
function getData(last) {
db.transaction(function (tx) {
alert("get data");
var query = "SELECT firstname, lastname, acctNo FROM customerAccounts WHERE lastname = ?";
alert("get data working");
tx.executeSql(query, [last], function (tx, resultSet) {
for(var x = 0; x < resultSet.rows.length; x++) {
alert("First name: " + resultSet.rows.item(x).firstname +
", Acct: " + resultSet.rows.item(x).acctNo);
}
},
function (tx, error) {
alert('SELECT error: ' + error.message);
});
}, function (error) {
alert('transaction error: ' + error.message);
}, function () {
alert('transaction ok');
});
}
///////////////////////////////////////////////////////////////////////////////////////////////////
}
I did it with sql.js and xml http request using following piece of code:
var xhr = new XMLHttpRequest();
xhr.open('GET', 'yourDBname.db', true);
xhr.responseType = 'arraybuffer';
xhr.onload = function(e)
{
mId = sessionStorage.i;
var uInt8Array = new Uint8Array(this.response);
var db = new SQL.Database(uInt8Array);
var contents = db.exec("SELECT * FROM ....your query");
// Do as per requirment
}
I m developing Android application. I'm integrating the sqlite into my application https://github.com/brodyspark/PhoneGap-sqlitePlugin-Android
The below error is coming
Uncaught TypeError: Object # has no method 'exec'
while using the following code
window.sqlitePlugin.openDatabase({name: "DB"});
You need to ensure you have waited for Cordova to load prior to opening a database.
As per the README.md from the project:
// Wait for Cordova to load
document.addEventListener("deviceready", onDeviceReady, false);
// Cordova is ready
function onDeviceReady() {
var db = window.sqlitePlugin.openDatabase({name: "my.db"});
// ...
}
https://github.com/xuexueMaGicK/Gift-App
see this link js file is available here database connection are there
window.addEventListener("DOMContentLoaded", init);
function init() {
pageshow = document.createEvent("Event");
pageshow.initEvent("pageshow", true, true);
tap = document.createEvent("Event");
tap.initEvent("tap", true, true);
pages = document.querySelectorAll('[data-role="page"]');
numPages = pages.length;
links = document.querySelectorAll('[data-role="link"]');
numLinks = links.length;
//checkDB();
document.addEventListener("deviceready", checkDB, false);
}
/*******************************
General Interactions
*******************************/
function checkDB() {
navigator.splashscreen.hide();
database = openDatabase('data', '', 'data', 1024 * 1024);
if (database.version === '') {
database.changeVersion('', '1.0', createDB, function (tx, err) {
console.log(err.message);
}, function (tx, rs) {
console.log("Increment transaction success.");
});
addNavHandlers();
} else {
addNavHandlers();
}
}
function createDB(db)
{
/*******Create Table Gifts********/
db.executeSql('CREATE TABLE "gifts" ("gift_id" INTEGER PRIMARY KEY AUTOINCREMENT, "name_id" INTEGER, "occasion_id" INTEGER, "gift_idea" VARCHAR(45))', [], function (tx, rs) {
console.log("Table gifts created");
}, function (tx, err) {
console.log(err.message);
});
/*******Create Table Names********/
db.executeSql('CREATE TABLE "names" ("name_id" INTEGER PRIMARY KEY AUTOINCREMENT, "name_text" VARCHAR(80))', [], function (tx, rs) {
console.log("Table names created");
}, function (tx, err) {
console.log(err.message);
});
/*******Create Table Occasions********/
db.executeSql('CREATE TABLE "occasions" ("occasion_id" INTEGER PRIMARY KEY AUTOINCREMENT, "occasion_text" VARCHAR(80))', [], function (tx, rs) {
console.log("Table occasions created");
}, function (tx, err) {
console.log(err.message);
});
}
In Manifest.xml u have to add plugins related to the SQLite.Then it will work.