本文讲解的是使用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;
}
};