问题
I am new to ionic 1. I connected my app with sqlite. I want to see the table data that are inserted. And display the inserted data in the console. But, I can't figure out Why row length is still 0. And there is no error on console. Here's my controller code snippet:
.controller('salesCtrl', ['$scope', '$stateParams','$cordovaSQLite', // The following is the constructor function for this page's controller. See https://docs.angularjs.org/guide/controller
// You can include any angular dependencies as parameters for this function
// TIP: Access Route Parameters for your page via $stateParams.parameterName
function ($scope, $stateParams,$cordovaSQLite) {
var db=null;
if (window.cordova) {
db = $cordovaSQLite.openDB({ name: "pos.db" }); //device
console.log("not in browser");
}else{
db = window.openDatabase("pos.db", '1', 'my', 1024 * 1024 * 100); // browser
console.log("browser");
}
$cordovaSQLite.execute(db,"CREATE TABLE IF NOT EXISTS items(id integer primary key AUTOINCREMENT,firstname text NOT NULL,lastname text NOT NULL)");
$scope.insert=function(){
var query="INSERT into items(firstname,lastname) VALUES(?,?)";
$cordovaSQLite.execute(db,query,["name1","name2"]).then(function(result){
console.log(result.rows);
},function(error){
console.log(error);
})
}
}])
and here is my template page code snippet in which when someone click the button it will call the insert()
function.
<ion-item class="item-icon-left" id="sales-list-item4" ui-sref="menu.itemQuantity">
<i class="icon ion-android-checkbox-blank"></i>
<button class="button button-icon icon ion-ios-cart-outline" ng-click="insert()"> click</button>
<span class="item-note">600 </span>
</ion-item>
回答1:
One thing to check is be sure that you are opening the DB in or after deviceready has fired.
If you are doing it before deviceready the window.openDatabase will succeed but the $cordovaSQLite.openDB will likely fail. Wrapped with ionicPlatform ready everytimes you want to run the sqlite.
.controller('salesCtrl', ['$scope', '$stateParams','$cordovaSQLite', '$ionicPlatform',
function ($scope, $stateParams,$cordovaSQLite, $ionicPlatform) {
$ionicPlatform.ready(function () {
var db=null;
if (window.cordova) {
db = $cordovaSQLite.openDB({ name: "pos.db" }); //device
console.log("not in browser");
} else{
db = window.openDatabase("pos.db", '1', 'my', 1024 * 1024 * 100); // browser
console.log("browser");
}
$cordovaSQLite.execute(db,"CREATE TABLE IF NOT EXISTS items(id integer primary key AUTOINCREMENT,firstname text NOT NULL,lastname text NOT NULL)");
});
$scope.insert=function(){
$ionicPlatform.ready(function () {
var query="INSERT into items(firstname,lastname) VALUES(?,?)";
$cordovaSQLite.execute(db,query,["name1","name2"]).then(function(result){
console.log(result.rows);
},function(error){
console.log(error);
});
}
});
}
}])
来源:https://stackoverflow.com/questions/42747576/cant-insert-data-in-sqlite-table-in-ionic-1