javascript - 我无法在 cordova-sqlite-storage 中为 ionic 1 打开数据库

标签 javascript android sqlite cordova ionic-framework

我是 ionic 1 的新手,在 sqlite 存储中创建数据库时遇到很多问题。你能帮我吗?

我正在使用上面名称的插件“cordova-sqlite-storage” 问题是,当代码传入 openDB 命令时,它会停在那里并且无法继续。

按照我的代码操作:

js/sqlite.js

var sqlite = angular.module('sqlite', ['ionic', 'ngCordova']);

sqlite.run(function ($ionicPlatform, $cordovaSQLite) {
    $ionicPlatform.ready(function () {
        var db = $cordovaSQLite.openDB({ name: "rollers.db", bgType: 1 });
        $cordovaSQLite.execute(db, "CREATE TABLE IF NOT EXISTS clientes (id integer primary key, razaoSocial varchar(40), nomeFantasia varchar(40), CNPJ text, Endereco text)");
        $cordovaSQLite.execute(db, "CREATE TABLE IF NOT EXISTS instalacao (id integer primary key, idCliente int, DataInst datetime)");
        $cordovaSQLite.execute(db, "CREATE TABLE IF NOT EXISTS manutencao (id integer primary key, idCliente int, idInstalacao int, DataManut datetime)");
        $cordovaSQLite.execute(db, "CREATE TABLE IF NOT EXISTS equipamento (id integer primary key, idInstalacao int, idManutencao int, TC int, Rolo varchar(40))");
    });
})

sqlite.factory('clientesFactory', function ($cordovaSQLite) {
    return {
        insert: function (firstname, lastname, avatar, message) {
            var query = "INSERT INTO clientes    (razaoSocial, nomeFantasia, CNPJ, Endereco) VALUES (?, ?, ?, ?);";
            var values = [firstname, lastname, avatar, message];

            $cordovaSQLite.execute(db, query, values).then(
              function (res) {
                  console.log('INSERTED ID: ' + res.insertId);
              },
              function (err) {
                  console.log('ERROR: ' + err);
              }
            );
        },

        insertInstalacao: function (idCliente, DataInst) {
            var query = "INSERT INTO instalacao  (idCliente, DataInst) VALUES (?, ?);";
            var values = [idCliente, DataInst];

            $cordovaSQLite.execute(db, query, values).then(
              function (res) {
                  console.log('INSERTED ID: ' + res.insertId);
              },
              function (err) {
                  console.log('ERROR: ' + err);
              }
            );
        },

        insertInstalacao: function (idCliente, idInstalacao, DataManut) {
            var query = "INSERT INTO manutencao  (idCliente, idInstalacao, DataManut) VALUES (?, ?, ?, ?);";
            var values = [idCliente, idInstalacao, DataManut];

            $cordovaSQLite.execute(db, query, values).then(
              function (res) {
                  console.log('INSERTED ID: ' + res.insertId);
              },
              function (err) {
                  console.log('ERROR: ' + err);
              }
            );
        },

        insertInstalacao: function (idInstalacao, idManutencao, TC, Rolo) {
            var query = "INSERT INTO equipamento (idInstalacao, idManutencao, TC, Rolo) VALUES (?, ?, ?, ?);";
            var values = [idInstalacao, idManutencao, TC, Rolo];

            $cordovaSQLite.execute(db, query, values).then(
              function (res) {
                  console.log('INSERTED ID: ' + res.insertId);
              },
              function (err) {
                  console.log('ERROR: ' + err);
              }
            );
        },

        select: function (id) {
            var query = "SELECT * FROM clientes WHERE id=?";
            var values = [id];

            $cordovaSQLite.execute(db, query, values).then(
              function (res) {
                  if (res.rows.length > 0) {
                      var first = res.rows.item(0);
                      console.log(res.rows.length + ' records, fist: ' + first.firstname + ' ' + first.lastname + ' - ' + first.avatar);
                  } else {
                      console.log('No records found');
                  }
              }
            );
        }
    }
});

index.html:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
    <title></title>

    <link href="lib/ionic/css/ionic.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">

    <!-- IF using Sass (run gulp sass first), then uncomment below and remove the CSS includes above
    <link href="css/ionic.app.css" rel="stylesheet">
    -->

    <!--For users deploying their apps to Windows 8.1 or Android Gingerbread, platformOverrided.js
    will inject platform-specific code from the /merges folder -->
    <script src="js/platformOverrides.js"></script>

    <!-- ionic/angularjs js -->
    <script src="lib/ionic/js/ionic.bundle.js"></script>
    <script src="lib/ngCordova/dist/ng-cordova.js"></script>

    <!-- cordova script (this will be a 404 during development) -->
    <script src="cordova.js"></script>

    <!-- your app's js -->
    <script src="js/sqlite.js"></script>
    <script src="js/app.js"></script>
    <script src="js/controllers.js"></script>
    <script src="js/services.js"></script>
  </head>
  <body ng-app="starter">
    <ion-nav-view></ion-nav-view>
  </body>
</html>

js/controller.js:

.controller('ClienteDetalheCtrl', function ($scope, clientesFactory) {
//.controller('ClienteDetalheCtrl', function ($scope){
    $scope.gravaCliente = function () {
        var primeiro_nome   = document.getElementById('TxtRazao').value;
        var segundo_nome    = document.getElementById('TxtFantasia').value;
        var avatar          = document.getElementById('TxtCNPJ').value;
        var mensagem        = document.getElementById('TxtEnd').value;
        clientesFactory.insert(primeiro_nome, segundo_nome, avatar, mensagem);
        clientesFactory.select(1);
        document.getElementById('TxtRazao').value = 'teste';
    }

    $scope.limpaCliente = function () {
        document.getElementById('TxtRazao').value = '';
        document.getElementById('TxtFantasia').value = '';
        document.getElementById('TxtCNPJ').value = '';
        document.getElementById('TxtEnd').value = '';
    }
})

app.js:

// Ionic Starter App

// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
// 'starter.services' is found in services.js
// 'starter.controllers' is found in controllers.js
SLAVE_AAPT_TIMEOUT = 30
angular.module('starter', ['ionic', 'starter.controllers', 'starter.services', 'sqlite'])
//angular.module('starter', ['ionic', 'starter.controllers', 'starter.services'])

.run(function ($ionicPlatform) {
    $ionicPlatform.ready(function () {
        // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
        // for form inputs)
        if (cordova.platformId === "ios" && window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard) {
            cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
            cordova.plugins.Keyboard.disableScroll(true);

        }
        if (window.StatusBar) {
            // org.apache.cordova.statusbar required
            StatusBar.styleDefault();
        }
    });
})

.config(function ($stateProvider, $urlRouterProvider) {

    // Ionic uses AngularUI Router which uses the concept of states
    // Learn more here: https://github.com/angular-ui/ui-router
    // Set up the various states which the app can be in.
    // Each state's controller can be found in controllers.js
    $stateProvider

    // setup an abstract state for the tabs directive
      .state('tab', {
          url: '/tab',
          abstract: true,
          templateUrl: 'templates/tabs.html'
      })

    // Each tab has its own nav history stack:

    .state('tab.home', {
        url: '/dash',
        views: {
            'tab-home': {
                templateUrl: 'templates/home.html',
                controller: 'HomeCtrl'
            }
        }
    })

    .state('tab.manutencao', {
        url: '/manutencao',
        views: {
            'tab-manutencao': {
                templateUrl: 'templates/manutencao.html',
                controller: 'InstalacaoCtrl'
            }
        }
    })

    .state('tab.instalacao', {
        url: '/instalacao',
        views: {
            'tab-instalacao': {
                templateUrl: 'templates/instalacao.html',
                controller: 'InstalacaoCtrl'
            }
        }
    })

    .state('tab.instalacao-detalhe', {
        url: '/instalacao-detalhe',
        views: {
            'tab-instalacao-detalhe': {
                templateUrl: 'templates/instalacao-detalhe.html',
                controller: 'InstalacaoDetalheCtrl'
            }
        }
    })

    .state('tab.cliente', {
        url: '/cliente',
        views: {
            'tab-cliente': {
                templateUrl: 'templates/cliente.html',
                controller: 'ClienteCtrl'
            }
        }
    })

    .state('tab.cliente-detalhe', {
        url: '/cliente-detalhe',
        views: {
            'tab-cliente-detalhe': {
            templateUrl: 'templates/cliente-detalhe.html',
            controller: 'ClienteDetalheCtrl'
            }
        }
    });

    // if none of the above states are matched, use this as the fallback
    $urlRouterProvider.otherwise('/tab/dash');

});

如果大家能帮助我,我将非常感激。

感谢您的关注。

最佳答案

在 sqlite.js 中尝试一下

sqlite.run(function ($ionicPlatform, $cordovaSQLite) {
$ionicPlatform.ready(function () {
var db = $cordovaSQLite.openDB({ name: "rollers.db", location: 'default' });
    $cordovaSQLite.execute(db, "CREATE TABLE IF NOT EXISTS clientes (id integer primary key, razaoSocial text, nomeFantasia text, CNPJ text, Endereco text)");
    $cordovaSQLite.execute(db, "CREATE TABLE IF NOT EXISTS instalacao (id integer primary key, idCliente integer, DataInst text)");
    $cordovaSQLite.execute(db, "CREATE TABLE IF NOT EXISTS manutencao (id integer primary key, idCliente integer, idInstalacao integer, DataManut text)");
    $cordovaSQLite.execute(db, "CREATE TABLE IF NOT EXISTS equipamento (id integer primary key, idInstalacao integer, idManutencao integer, TC integer, Rolo text)");
});
});

关于javascript - 我无法在 cordova-sqlite-storage 中为 ionic 1 打开数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43262914/

相关文章:

javascript - EasyQuery - 通过代码添加子查询

java - 无法使用Android在mysql中插入数据

iphone - 如果记录已存在于 iphone sqlite 中,则阻止插入

javascript - 如何在更改事件完成之前更新 DOM?

javascript - 来自 EventListener 的 ReactJS 事件不会更新 View

android - RxJava2 - 同步执行调用

java - 是否可以从同一个 SQLite 数据库中检索文本和图像

SQLITE3 将文本和数字存储在同一列中

c++ - 如何使用sqlite3 C++将整数转换为字符串

javascript - 如何使用css和vue.js查找表格行元素?