import React,{Component} from 'react';
import{
ToastAndroid,
NativeModules,
Alert,
BackHandler
} from 'react-native';
import SQLiteStorage from 'react-native-sqlite-storage';
SQLiteStorage.DEBUG(true);
//项目中用的是可以插SD卡的android设备
///storage/EDB8-F24B/Handheld/handheld.db /sdcard/Handheld/
var database_version = "1.0";//版本号
var database_displayname = "MySQLite";
var database_size = -1;//-1应该是表示无限制
var db;
var localDb;
export default class SQLite extends Component{
componentWillUnmount(){
if(db){
this._successCB('close');
db.close();
}else {
console.log("SQLiteStorage not open");
}
}
componentWillMount(){
}
//
openCardDb(){
db = SQLiteStorage.openDatabase(
cardPath+"/Handheld/"+dbName+".db",//数据库文件 SD卡指定路径
database_version,
database_displayname,
database_size,
()=>{
this._successCB('open');
},
(err)=>{
this._errorCB('open',err);
});
return db;
}
openLocalDb(){
console.log("调用打开数据库openLocalDb");
localDb = SQLiteStorage.openDatabase(
"/sdcard/Handheld/"+dbName+".db",//数据库文件 内部存储路径
database_version,
database_displayname,
database_size,
()=>{
this._successCB('open');
},
(err)=>{
this._errorCB('open',err);
});
return localDb;
}
createTable(){
if (!db) {
this.open();
}
//创建用户表
db.transaction((tx)=> {
tx.executeSql('CREATE TABLE IF NOT EXISTS USER(' +
'id INTEGER PRIMARY KEY AUTOINCREMENT,' +
'name varchar,'+
'age VARCHAR,' +
'sex VARCHAR,' +
'phone VARCHAR,' +
'email VARCHAR,' +
'qq VARCHAR)'
, [], ()=> {
this._successCB('executeSql');
}, (err)=> {
this._errorCB('executeSql', err);
});
}, (err)=> {//所有的 transaction都应该有错误的回调方法
this._errorCB('transaction', err);
}, ()=> {
this._successCB('transaction');
})
}
deleteData(){//删除表中的数据
if (!db) {
this.open();
}
db.transaction((tx)=>{
tx.executeSql('delete from user',[],()=>{
});
});
}
dropTable(){//删除表
db.transaction((tx)=>{
tx.executeSql('drop table user',[],()=>{
});
},(err)=>{
this._errorCB('transaction', err);
},()=>{
this._successCB('transaction');
});
}
close(){
if(db){
this._successCB('close');
db.close();
}else {
console.log("SQLiteStorage not open");
}
db = null;
}
_successCB(name){
console.log("SQLiteStorage "+name+" success");
}
_errorCB(name, err){
console.log("SQLiteStorage "+name);
console.log(err);
}
async execSql(localDb,cardDb,sql,successFunction,endFunction){
if(cardPath!="/sdcard"){
//如果获取到的路径有SD卡
if(!localDb){
localDb = this.openLocalDb();
}
if(!cardDb){
cardDb = this.openCardDb();
}
//项目中需要两个地方存储数据库
await cardDb.transaction((tx)=>{
tx.executeSql(sql, [],(tx,results)=>{
successFunction(tx,results);
});
},(error)=>{//打印异常信息
},()=>{
endFunction();
});
localDb.transaction((tx)=>{
tx.executeSql(sql, [],(tx,results)=>{
console.log("数据库执行成功"+sql)
});
},(error)=>{//打印异常信息
},()=>{
});
}else{
//如果获取到的路径有SD卡
if(!localDb){
localDb = this.openLocalDb();
}
localDb.transaction((tx)=>{
tx.executeSql(sql, [],(tx,results)=>{
successFunction(tx,results);
});
},(error)=>{//打印异常信息
},()=>{
endFunction();
});
}
}
render(){
return null;
}
};