How to implement SQLite from ngCordova in ionic

3

Trying to implement the SQLite ngCordova plugin, I have encountered confusion about how to implement the plugin, because in the official page it appears in one way, and in the github repository in another.

ngCordova Plugin

GitHub Repository

Here is the code

Example 1

No error occurs in this example, but the database does not work, nothing happens, it does not save anything.

angular.module('unicesarApp', ['ionic', 'historialApp'])
       .controller('formulario', formulario)
       .service('obtenerDatos', obtenerDatos)
       .config(config);

formulario.$inject = ['$scope', 'obtenerDatos', '$state', '$timeout'];

function formulario($scope, obtenerDatos, $state, $timeout){

    $scope.login = function(){


        var datos, datosRespuesta;

        datos = {
            Usuario: $scope.usuariotxt,
            Password: $scope.passwordtxt
        };

        if(datos.Usuario == undefined && datos.Password == undefined){

            $scope.respuesta = "Los campos estan vacios";

        }else{                

            $state.go('Loading');
            //$scope.respuesta = "Solicitando informacion";

            obtenerDatos.Autenticacion(datos).then(function(response) {

              if(response.data) {

                datosRespuesta = response.data;

                  if (datosRespuesta === "Usuario no registrado" || 
                      datosRespuesta === "Contraseña incorrecta") {

                      $timeout(function() {
                          $scope.respuesta = datosRespuesta;
                          $state.go('login');
                        }, 2000);


                  } else {        

                        if (datosRespuesta.estudiante){

                            console.log(datosRespuesta.estudiante);

                            var db, Perfil;

                            db = window.sqlitePlugin.openDatabase({name: "unicesar.db", createFromLocation: 1});

                            Perfil = datosRespuesta.estudiante;

                            db.transaction(function(tx){

                                var crearTablaPerfil, queryInsertar, queryConsulta;


                                crearTablaPerfil = "CREATE TABLE IF NOT EXISTS Estudiante(Cedula integer primary key, Nombre text,   Apellido text, Rol integer, Facultad text, Programa text, Semestre integer)";

                                queryInsertar = "INSERT INTO Estudiante(Cedula, Nombre, Apellido, Rol, Facultad, Programa, Semestre)  VALUES(?,?,?,?,?,?,?)";

                                queryConsulta = "SELECT * FROM Estudiante";

                                tx.executeSql(crearTablaPerfil);

                                tx.execute(db, queryInsertar, [Perfil.CeduEstu, Perfil.NombEstu, Perfil.ApelEstu,    Perfil.RolEstu, Perfil.FacuEstu, Perfil.ProgEstu, Perfil.Semestre]);

                                tx.executeSql(queryConsulta, [], function(tx, result) {

                                    var row;

                                     if(result.rows.length > 0) {

                                         row = result.rows.item(0);

                                         alert("Datos:", row.Cedula +" "+ row.Nombre +" "+ row.Apellido +" "+ row.Rol +" "+ row.Facultad +" "+ row.Programa +" "+ row.Semestre);

                                     };  

                                }, 

                                function(e){
                                    console.log("error: "+e.message);
                                });

                            }); 

                            $state.go('Loading');

                            $timeout(function() {
                                $state.go(datosRespuesta.estudiante ? 'menuestu' : 'menuprof');
                            }, 3000);      

                    }else {

                         console.log(response.status);
                         $scope.respuesta = "Error en la solicitud";
                         $state.go('login');

                        };     



                 };

             };

          });

        };

    };
};

Example 2

Using this form, an error is generated that the browser does not show me, only that when compiling and obtaining the apk, and then installing it, the main view of the application appears blank, therefore the app does not work.

angular.module('unicesarApp', ['ionic', 'historialApp', 'ngCordova'])
       .controller('formulario', formulario)
       .service('obtenerDatos', obtenerDatos)
       .config(config);

formulario.$inject = ['$scope', 'obtenerDatos', '$state', '$timeout', '$cordovaSQLite'];

function formulario($scope, obtenerDatos, $state, $timeout, $cordovaSQLite){

    $scope.login = function(){


        var datos, datosRespuesta;

        datos = {
            Usuario: $scope.usuariotxt,
            Password: $scope.passwordtxt
        };

        if(datos.Usuario == undefined && datos.Password == undefined){

            $scope.respuesta = "Los campos estan vacios";

        }else{                

            $state.go('Loading');
            //$scope.respuesta = "Solicitando informacion";

            obtenerDatos.Autenticacion(datos).then(function(response) {

              if(response.data) {

                datosRespuesta = response.data;

                  if (datosRespuesta === "Usuario no registrado" || 
                      datosRespuesta === "Contraseña incorrecta") {

                      $timeout(function() {
                          $scope.respuesta = datosRespuesta;
                          $state.go('login');
                        }, 2000);


                  } else {        

                        if (datosRespuesta.estudiante){

                            console.log(datosRespuesta.estudiante);

                            var db, Perfil, row, crearTablaPerfil, guardarPerfil, consultaPerfil; 

                            Perfil = datosRespuesta.estudiante;

                            db = $cordovaSQLite.openDB({ name: "unicesar.db" });

                            crearTablaPerfil = "CREATE TABLE IF NOT EXISTS Estudiante(Cedula integer primary key, Nombre text,   Apellido text, Rol integer, Facultad text, Programa text, Semestre integer)";

                            guardarPerfil = "INSERT INTO Estudiante(Cedula, Nombre, Apellido, Rol, Facultad, Programa, Semestre)  VALUES(?,?,?,?,?,?,?)";

                            consultaPerfil = "SELECT * FROM Estudiante";

                            $cordovaSQLite.execute(db, crearTablaPerfil);

                            $cordovaSQLite.execute(db, guardarPerfil, [Perfil.CeduEstu, Perfil.NombEstu, Perfil.ApelEstu,    Perfil.RolEstu, Perfil.FacuEstu, Perfil.ProgEstu, Perfil.Semestre]);

                            $cordovaSQLite.execute(db, consultaPerfil).then(function(result){

                                if(result.rows.length > 0) {

                                    row = result.rows.item(0);

                                    alert("Datos:", row.Cedula +" "+ row.Nombre +" "+ row.Apellido +" "+ row.Rol +" "+ row.Facultad +" "+ row.Programa +" "+ row.Semestre);


                                $state.go('Loading');

                                $timeout(function() {
                                    $state.go(datosRespuesta.estudiante ? 'menuestu' : 'menuprof');
                                }, 3000); 



                    }else {

                         console.log(response.status);
                         $scope.respuesta = "Error en la solicitud";
                         $state.go('login');

                        };     



                 };

             };

          });

        };

    };
};

If someone knows what the error could be, I would thank you in advance.

    
asked by Pedro Miguel Pimienta Morales 10.04.2016 в 01:19
source

1 answer

1

First, the ngCordova project is no longer supported, which is why it is sometimes deactivated with respect to official documentation.

With SQLite this happens, the documentation of ngCordova is not updated, the plugin recently made some changes, so that it works you should create the database in this way:

 DB = $cordovaSQLite.openDB({
  name: 'app.db',
  location: 'default',
  iosDatabaseLocation: 'Library'
});

These last two parameters location and iosDatabaseLocation are not in the ngCordova documentation but in the plugin documentation if they are and are mandatory, this simply does not create the database so it could be the cause of your problem.

Bye!

    
answered by 07.06.2016 в 02:46