A simple SQLite dual backup code

Source: Internet
Author: User
Tags sqlite sqlite database

In the process of using the database, if the database file is created only in internal memory, it may be deleted resulting in data loss (the SQLite file that is deleted after Root enters Data/data), in order to prevent this situation, the database file can be backed up in SDcard. The following is a simple two-backup database code class, the main function is to implement in the database key-value pair storage, and the database and stored in the internal memory, and saved in SDcard.

/** *  @author  xiaoli *  Below is a database double backup using instance code, the advantage of dual backup is that if the user mistakenly deleted the internal memory in the database file we can still read the external memory database  */public class DoubleBackUpDB{private String DB_NAME =  ". Doublebackupdb.db ";p rivate static object syncobj = new object ();//Internal memory path public  final string privatedbpath;//External Memory path (sdcard) public final string sdcarddbpath;// Table name STRING TBL_NAME;//SQ Create statement string create_tbl;/** *  CREATE DATABASE  *  @param  path  Database creation Path  */void createdb (string path ) {sqlitedatabase db = null;try{db  = getdatabase ( path );} catch ( Exception e ) {}try{db.close ();} catch ( Exception ex ) {}}/** *  *  @param  context *  @param The  sdcardDbPath  constructor needs to pass in the SDcard path to the database,  *  @param  moduleName  is the name of the database, for the sake of uniqueness of the table, Easy to construct different dual backup database files each time.  */public doublebackupdb (Context context ,string sdcarddbpath ,string modulename ) {This ( context ,  sdcardDbPath , moduleName , null );} /** *  *  @param  context *  @param  sdcardDbPath  The SDcard path that the constructor needs to pass into the database  *  @param  moduleName  is the name of the database, which makes it easy to construct a different dual backup database file each time for uniqueness.  *   @param  dbFileName  You can rename the DB file name (or null to use the default)  */public doublebackupdb (context  context ,string sdcarddbpath ,string modulename ,string dbfilename ) {this. Tbl_name = modulename;if ( dbFileName != null ) {this. Db_name = dbfilename;} This. create_tbl =  "create table if not exists "  + TBL_NAME +   "("  +  "Key text primary key not null,"  +  "Value text")  +  ")"; This.privatedbpath = context.getfilesdir (). GetabsolutePath ()  +  "/"  + moduleName + DB_NAME;try{PackageInfo pkgInfo =  Context.getpackagemanager (). Getpackageinfo ( context.getpackagename ()  , 0 ) Sdcarddbpath  = sdcardDbPath +  "/"  + pkginfo.packagename + pkginfo.versionname  + modulename + db_name;} catch ( Exception e ) {sdcarddbpath = sdcarddbpath +  "/"  +  Context.getpackagename ()  + modulename + db_name;} This.sdcarddbpath = sdcarddbpath;synchronized ( syncObj ) {createdb ( this.privatedbpath  ); Createdb ( this.sdcardDbPath );}} /** *  *  @param  dbPath  Database creation path  *  @return  sqlite database  */ Private sqlitedatabase getdatabase (string dbpath ) {try{new file (  Dbpath.substring ( 0 , dbpath.lastindexof (  " )  )  ). Mkdirs (); SqlitedataBase db = sqlitedatabase.openorcreatedatabase ( dbPath , null ); try{ Db.execsql ( CREATE_TBL );} catch ( Exception ex ) {}return db;} catch ( Exception e ) {new file ( dbpath.substring ( 0 ,  Dbpath.lastindexof (  "/"  )  )  ). Mkdirs (); Sqlitedatabase db = sqlitedatabase.openorcreatedatabase ( dbPath , null ); Try{db.execsql ( CREATE_TBL );} catch ( Exception ex ) {}return db;}} Public void setvalue (string key ,integer value ) {SetValue ( key ,  Value != null ? value.longvalue ()  : null );} Public void setvalue (string key ,long value ) {SetValue ( key ,  Value != null ? value.tostring ()  : null );} Public void setvalue (string key ,string value ) {sYnchronized ( syncObj ) {setstringtodb ( privateDbPath , key , value ); Setstringtodb ( sdcardDbPath , key , value );}} Public integer getint (string key ) {return getint ( key , null );} Public integer getint (string key ,integer defaultvalue ) {Long result =  getlong ( key ); if ( result == null ) {return defaultvalue;} Return result.intvalue ();} Public long getlong (string key ) {Return getlong ( key , null );} Public long getlong (string key ,long defaultvalue ) {try{return  Long.parselong ( getstring ( key )  );} catch ( Exception e ) {return defaultvalue;}} Public string getstring (string key ,string defaultvalue ) {String result  = getstring ( key ); if ( result == null ) {return defaultvalue;} Return result;} Public string getstring (string key ) {synchronized ( syncObj ) {String value  = getstringfromdb ( privateDbPath , key ); if ( value == null  ) {Value = getstringfromdb ( sdcardDbPath , key );} Return value;}} /** *  querying the database for the corresponding content  *  @param  dbPath  database path  *  @param  key  key values by key value  *  @return   Query Results  */private string getstringfromdb (string dbpath ,string  key ) {string value = null; sqlitedatabase db = null; Cursor c = null;try{db = getdatabase ( dbPath ); C = db.query (  TBL_NAME , null ,  "key="  + key +  "'"  , NULL   null , null , null ); if ( c.movetoFirst ()  ) {value = c.getstring ( 1 );}} catch ( Exception e ) {}finally{try{c.close ();} catch ( Exception e ) {}try{db.close ();} catch ( Exception e ) {}}return value;} /** *  Store content to database  *  @param  dbPath  database path  *  @param  key  key value  *   @param  value  Actual deposit value  */private void setstringtodb (string dbpath ,string  key ,String value ) {sqlitedatabase db = null; Cursor c = null;try{db = getdatabase ( dbPath ); if ( value !=  null ) {contentvalues content = new contentvalues (); Content.put (  "key"  ,  key ); Content.put (  "value"  , value ); C = db.query ( tbl_name  , null ,  "key="  + key +  "'"  , NULL , NULL   null , null ); if( c.movetofirst ()  ) {db.update ( TBL_NAME , content ,  "key=" " + key + " " ,  null );} Else{db.insert ( TBL_NAME , null , content );}} Else{db.delete ( TBL_NAME ,  "key=" " + key + " " , null );}} catch ( Exception e ) {}finally{try{c.close ();} catch ( Exception e ) {}try{db.close ();} catch ( Exception e ) {}}}

Attachments have been uploaded and can be used directly to modify them.

A simple SQLite dual backup code

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.