React-Native SQLite遇到的坑

本文讲解的是使用react-native-sqilte-storage库,github地址:https://github.com/andpor/react-native-sqlite-storage

以下为一个使用示例,这里尤其要注意insert的时候,一定要检查插入的数据格式跟数据库表定义的格式是否一致,如果不一致,插入的时候会失败,而且没有任何错误,感觉像是sql没执行

我这里就遇到把一个obj插入一个varchar类型的字段时死活不能写数据的情况,一定要慎重!!!

 

import React,{Component} from 'react';

 

import SQLiteStorage from 'react-native-sqlite-storage';

SQLiteStorage.DEBUG(true);

var database_name = "notify.db";//数据库文件

var database_version = "1.0";//版本号

var database_displayname = "notifyDB";

var database_size = -1;//-1应该是表示无限制

var db;

export default class  SQLiteHelper extends Component{

  constructor(props){

    super(props)

    console.log("SQLiteStorage constructor");

  }

 

  //在组件被销毁的时候关闭数据库连接

  componentWillUnmount(){

    console.log("SQLiteStorage componentWillUnmount");

    if(db){

        this._successCB('close');

        db.close();

    }else {

        console.log("SQLiteStorage not open");

    }

  } 

 

  //打开数据库连接

  open = () =>{

    console.log("SQLiteStorage open");

    db = SQLiteStorage.openDatabase(

      database_name,

      database_version,

      database_displayname,

      database_size,

      ()=>{

          this._successCB('open');

      },

      (err)=>{

          this._errorCB('open',err);

      }

    );

    return db;

  }

 

 

  //删除整张表数据

  deleteData = () =>{

    if (!db) {

        this.open();

    }

    db.transaction((tx)=>{

      tx.executeSql('delete from notify',[],()=>{

 

      });

    });

  }

 

  //删除表

  dropTable = () =>{

    db.transaction((tx)=>{

      tx.executeSql('drop table notify',[],()=>{

 

      });

    },(err)=>{

      this._errorCB('transaction', err);

    },()=>{

      this._successCB('transaction');

    });

  }


 

  //向数据库表插入数据

  insertNotifyData = (notifyData) => {

    console.log('SQLiteStorage insertNotifyData');

    if (!db) {

      this.open();

    }

    //如果表不存在先创建表

    /**本地存储的通知消息表字段如下:

     * notify_user_id   当前登录用户id

     * notify_type   通知类型,0:系统通知;1:系统公告;2:平台活动

     * notify_message_id  唯一标识一条通知消息的id

     * notify_time   接收到通知的时间(yyyy-MM-dd HH:mm:ss)

     * notify_title  通知消息的标题

     * notify_content  通知消息的内容

     * notify_extras  通知消息的附加内容

     * notify_state     通知消息的状态,0:未读;1:已读

     */

    db.executeSql('CREATE TABLE IF NOT EXISTS NOTIFY (' +

              'id INTEGER PRIMARY KEY AUTOINCREMENT,' +

              'notify_user_id VARCHAR,'+

              'notify_type VARCHAR,'+

              'notify_message_id VARCHAR,' +

              'notify_time VARCHAR,' +

              'notify_title VARCHAR,' +

              'notify_content VARCHAR,' +

              'notify_extras VARCHAR,' +

              'notify_state INTEGER)');

    let len = notifyData.length;

    /**本地存储的通知消息表字段如下:

       * notify_user_id 通知的用户id,用来唯一标识某一个用户

       * notify_type   通知类型,0:系统通知;1:系统公告;2:平台活动

       * notify_message_id  唯一标识一条通知消息的id

       * notify_time   接收到通知的时间(yyyy-MM-dd HH:mm:ss)

       * notify_title  通知消息的标题

       * notify_content  通知消息的内容

       * notify_extras  通知消息的附加信息

       * notify_state     通知消息的状态,0:未读;1:已读

       */

      for(let i=0; i<len; i++){

        let notify = notifyData[i];

        console.log("notify: " + JSON.stringify(notify));

        //执行insert的时候一定要注意数据类型,尤其这里notify.notifyExtras,一定要是字符串类型才行,否则insert语句不执行

        db.executeSql("INSERT INTO NOTIFY (notify_user_id, notify_type, notify_message_id, notify_time, notify_title, notify_content, notify_extras, notify_state) values(?,?,?,?,?,?,?,?)", 

          [notify.notifyUserId, notify.notifyType, notify.notifyMessageId, notify.notifyTime, notify.notifyTitle, notify.notifyContent, notify.notifyExtras, notify.notifyState],

          (success)=>{

            console.log('insertNotifyData executeSql success: ' + JSON.stringify(success));

          },(err)=>{

            console.log('insertNotifyData executeSql error: ' + JSON.stringify(err));

          }

        );

      }

  }


 

  //查询表中数据

  queryNotifyData = (params, callback) =>{

    console.log("SQLiteStorage queryNotifyData");

    if (!db) {

        this.open();

    }

    //查询

    db.executeSql("select * from notify where notify_user_id =? order by notify_time desc", [params.userId], (results)=>{

      console.log('queryNotifyData' + JSON.stringify(results));

      var len = results.rows.length;

      let result=[]

      //遍历处理返回数组的格式,方便界面上渲染处理

      for(let i=0; i<len; i++){

          result.push(results.rows.item(i))

      }

      console.log('queryNotifyData executeSql success: ' + JSON.stringify(result));

      callback&&callback(true, result)

    }, (error) =>{

      console.log('queryNotifyData executeSql fail: ' + JSON.stringify(error));

      callback&&callback(false, error)

    });

  }

 

  //将所有消息的状态更新为已读

  updateNotifyData = (params, callback) =>{

    console.log("SQLiteStorage updateNotifyData");

    if (!db) {

      this.open();

    }

    db.transaction((tx)=>{

      tx.executeSql("update notify set notify_state=1 where notify_user_id=?", [params.userId], 

        (tx, result)=>{

          console.log('updateNotifyData' + JSON.stringify(result));

          callback&&callback(true, result)

        }, 

        (error)=>{

          console.log('updateNotifyData error: ' + JSON.stringify(error));

          callback&&callback(false, result)

        }

      );

    }, (transactionSuccess) =>{

      console.log('updateNotifyData transactionSuccess: ' + JSON.stringify(transactionSuccess));

    }, (transactionError) =>{

      console.log('updateNotifyData transactionError: ' + JSON.stringify(transactionError));

    })

  }

 

  //判断是否还有未读的消息,true表示有,false表示没有

  hasUnReadableMessage = (params, callback) =>{

    if (!db) {

      this.open();

    }

    db.executeSql("select * from notify where notify_user_id =? and notify_state=0", [params.userId], 

        (results)=>{

          console.log('hasUnReadableMessage executeSql success' + JSON.stringify(results));

          //查询到数据

          if(results.rows.length > 0){

            callback&&callback(true)

          }else{

            callback&&callback(false)

          }

        }, 

        (error)=>{

          console.log('hasUnReadableMessage executeSql error: ' + JSON.stringify(error));

          callback&&callback(false)

        }

      );

  }

 

  //关闭数据库连接

  close = () =>{

    console.log("SQLiteStorage close");

    if(db){

        this._successCB('close');

        db.close();

    }else {

        console.log("SQLiteStorage not open");

    }

    db = null;

  }

 

  _successCB = (name) =>{

    console.log("_successCB SQLiteStorage "+name+" success");

  }

 

  _errorCB = (name, err) =>{

    console.log("SQLiteStorage " + name);

    console.log('_errorCB error: ' + err);

  }

 

  render(){

      return null;

  }

 

};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

晒干的老咸鱼

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值