【问题标题】:Create Database in SQLite with IONIC 3 + CORDOVA使用 IONIC 3 + CORDOVA 在 SQLite 中创建数据库
【发布时间】:2019-01-28 06:05:02
【问题描述】:

我正在使用 SQLite 开发一个应用程序,用于创建和列出用户...

为此我创建了一个服务,在该服务中我创建了数据库和两个方法(create 和 list),应该提到没有错误,并且我已经正确导入了所有内容

数据库.ts:

@Injectable()
export class DatabaseProvider {

  private db: SQLiteObject;
  private isOpen: boolean;

  constructor(
    public http: Http,
    public storage: SQLite) {

      if(!this.isOpen){
        this.storage = new SQLite();
        this.storage.create({ name: "data.db", location:"default" }).then((db:SQLiteObject) => {
          this.db = db;
          db.executeSql("CREATE TABLE IF NOT EXIST usuarios (Codigo INTEGER PRIMARY KEY AUTOINCREMENT, Identificacion INTEGER, Nombre TEXT, Apellido TEXT)", []);
          this.isOpen = true;
        }).catch((error) => {
          console.log(error);
        })
      }
      }

crearUsuario(Identificacion:number, Nombre:string, Apellido:string){
  return new Promise ((resolve , reject) => {
    let sql = "INSERT INTO usuarios (Identificacion, Nombre, Apellido) VALUES (?, ?, ?)";
    this.db.executeSql(sql, [Identificacion, Nombre, Apellido]).then((data) => {
      resolve(data);
    }, (error) => {
      reject(error);
    });  
  });
}

listarUsuario(){
  return new Promise ((resolve , reject) => {
    this.db.executeSql("SELECT * FROM usuarios", []).then((data) => {
      let arrayUsuarios = [];
      if(data.rows.length > 0){
        for (var i=0; i < data.rows.length; i++){
          arrayUsuarios.push({
            Codigo: data.rows.item(i).Codigo,
            Identificacion: data.rows.item(i).Identificacion,
            Nombre: data.rows.item(i).Nombre,
            Apellido: data.rows.item(i).Apellido,
          });
        }
      }
      resolve(arrayUsuarios);
    }, (error) => {
      reject(error);
    })
  });
}

}

在我看来 home.html 我有一个表单和两个按钮...一个列出用户,另一个创建表单的用户

home.html:

<button ion-button block color="secondary" (click)="listarUsuario()">Listar Usuario</button>

<form [formGroup]="todo" (ngSubmit)="crearUsuario()" novalidate>
  <ion-item>
    <ion-label>Nombre</ion-label>
    <ion-input type="text" formControlName="Nombre"></ion-input>
  </ion-item>
  <ion-item *ngIf="todo.get('Nombre').errors && todo.get('Nombre').dirty">     
  </ion-item>
  <ion-item>
    <ion-label>Apellido</ion-label>
    <ion-input type="text" formControlName="Apellido"></ion-input>
  </ion-item>
  <ion-item *ngIf="todo.get('Apellido').errors && todo.get('Apellido').dirty">      
  </ion-item>
  <ion-item>
    <ion-label>Indentificación</ion-label>
    <ion-input type="text" formControlName="Identificacion"></ion-input>
  </ion-item>
  <button ion-button block type="submit" [disabled]="!todo.valid">Crear Usuario</button>
</form>

<ion-list>
  <ion-item-sliding *ngFor="let item of listaPersonas">
    <ion-item>      
      <h2>{{item.Nombre}} - {{item.Apellido}}</h2>     
    </ion-item>   
    <ion-item-options side="right">
      <button ion-button color="danger">
        <ion-icon name="delete"></ion-icon>
        Eliminar
      </button>
    </ion-item-options> 
  </ion-item-sliding>
</ion-list>

我的控制器有以下代码:

home.ts:

export class HomePage {

  private listaPersonas: any;
  private todo: FormGroup;

  constructor(public navCtrl: NavController, private database: DatabaseProvider, private formBuilder: FormBuilder) {

    this.todo = this.formBuilder.group({
      Nombre: ['', [Validators.required, Validators.minLength(4), Validators.maxLength(8)]],
      Apellido: ['', [Validators.required, Validators.minLength(4), Validators.maxLength(8)]],
      Identificacion: ['', Validators.required],
    });

  } 

  crearUsuario(){
    console.log(this.todo);

      this.database.crearUsuario(this.todo.value.Identificacion, this.todo.value.Nombre, this.todo.value.Apellido).then((data) => {
        console.log(data);
        this.listarUsuario();
      }, (error) => {
        console.log(error);
      }) 
    }

  listarUsuario(){
    this.database.listarUsuario().then((data: any) => {
      console.log(data);
      this.listaPersonas = data;
    }, (error) => {
      console.log(error);
    })
  }    

}

我正在物理设备上测试我的应用程序,但它没有做任何事情......不要创建,不要列出用户,我想我没有创建数据库,我是 IONIC 3 的新手,并且要在物理设备上部署我的应用程序,我首先使用命令ionic cordova build android 构建,然后使用命令ionic cordova run android --device 在手机上部署我的应用程序

我做错了什么?如何通过在物理设备上尝试我的应用程序来找到错误?用我的调试控制台? Ionic 3 数据库物理存储在我的设备(目录)中的什么位置?对我有什么帮助吗?

【问题讨论】:

    标签: android sqlite cordova ionic-framework android-sqlite


    【解决方案1】:

    我相信您的问题是 :-

    的语法
    CREATE TABLE IF NOT EXIST usuarios (Codigo INTEGER PRIMARY KEY AUTOINCREMENT, Identificacion INTEGER, Nombre TEXT, Apellido TEXT)
    

    错了。

    即关键字是 EXISTS 而不是 EXIST。我建议尝试/使用:-

    db.executeSql("CREATE TABLE IF NOT EXISTS usuarios (Codigo INTEGER PRIMARY KEY AUTOINCREMENT, Identificacion INTEGER, Nombre TEXT, Apellido TEXT)", []); 
    

    【讨论】:

      【解决方案2】:

      要在 sqlite 中创建表,您需要先创建存储。你可以这样做:

       if (this.platform.is('cordova'))
                this.sqlite.create({
                  name: 'fundamentos.offline',
                  location: 'default'
                })
      .then((db: SQLiteObject) => {
          db.executeSql(CREATE TABLE IF NOT EXIST usuarios 
          (Codigo INTEGER PRIMARY KEY AUTOINCREMENT, Identificacion INTEGER, 
           Nombre TEXT, Apellido TEXT),[])
          .then(() => console.log('Table Created'))
          .catch(e => {
                      console.error(JSON.stringify(e));
                    });`
      

      供参考: https://ionicframework.com/docs/native/sqlite/ https://www.djamware.com/post/59c53a1280aca768e4d2b143/ionic-3-angular-4-and-sqlite-crud-offline-mobile-app

      【讨论】:

        猜你喜欢
        • 2014-12-29
        • 1970-01-01
        • 2021-07-19
        • 2016-10-24
        • 1970-01-01
        • 2015-11-24
        • 2018-12-24
        • 2018-03-17
        • 2018-04-14
        相关资源
        最近更新 更多