Author - StudySection Post Views - 211 views
SQLite

SQLite database in React Native (Android)

SQLite3 Native Plugin is supported by React Native for both Android (Classic and Native), iOS, and Windows. The Foundation of this library is based on Chris Brody’s Cordova SQLite plugin. This library is beneficial for those who want to store large amounts of data in their local storage.

Features:

  1. iOS and Android are supported via identical JavaScript API.
  2. Android in pure Java and Native modes
  3. SQL transactions
  4. JavaScript interface via plain callbacks or Promises.

There are sample apps provided in the test directory that can be used with your Project(AwesomeProject). All you have to do is to copy one of those files into your project(AwesomeProject) replacing index.ios.js.

The library has been tested with React 16.2 (and earlier) and XCode 7,8,9 – it works fine without any code changes. For XCode 7,8 vs. XCode 6. Version 3.2 is the version compatible with RN 0.40.

Installation

npm install --save react-native-sqlite-storage
Follow the following instructions to link react-native-SQLite-storage into your project

How to use (Android):
In React Native 0.60 and above there are no extra steps required to link dependencies.

For ** React Native 0.59 and below **
Step 1 -update settings.gradle file
// file: android/settings.gradle
...
include ':react-native-sqlite-storage'
project(':react-native-sqlite-storage').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-sqlite-storage/platforms/android') // react-native-sqlite-storage >= 4.0.0
// IMPORTANT: if you are working with a version less than 4.0.0 the project directory is '../node_modules/react-native-sqlite-storage/src/android'

Step 2 – Update app module Gradle Build script (Gradle settings in project pan)
// file: android/app/build.gradle
...
dependencies {
...
implementation project(':react-native-sqlite-storage')
}

Step 3 – Add the following code in Android/app/src/main/java/com/project/MainActivity.java
...
import org.pgsqlite.SQLitePluginPackage;
public class MainActivity extends Activity implements DefaultHardwareBackBtnHandler {
private ReactInstanceManager mReactInstanceManager;
private ReactRootView mReactRootView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mReactRootView = new ReactRootView(this);
mReactInstanceManager = ReactInstanceManager.builder()
.setApplication(getApplication())
.setBundleAssetName("index.android.bundle") // this is dependant on how you name you JS files, example assumes index.android.js
.setJSMainModuleName("index.android") // this is dependant on how you name you JS files, example assumes index.android.js
.addPackage(new MainReactPackage())
.addPackage(new SQLitePluginPackage()) // register SQLite Plugin here
.setUseDeveloperSupport(BuildConfig.DEBUG)
.setInitialLifecycleState(LifecycleState.RESUMED)
.build();
mReactRootView.startReactApplication(mReactInstanceManager, "AwesomeProject", null); //change "AwesomeProject" to name of your app
setContentView(mReactRootView);
}
...

Alternative approach on React Native (0.18+).
import org.pgsqlite.SQLitePluginPackage;
public class MainApplication extends Application implements ReactApplication {
......
/**
* A list of packages used by the app. If the app uses additional views
* or modules besides the default ones, add more packages here.
*/
@Override
protected List getPackages() {
return Arrays.asList(
new SQLitePluginPackage(), // register SQLite Plugin here
new MainReactPackage());
}
}

Step 4 – Require and use in Javascript – see full examples (callbacks and Promise) in the test directory.
// file: index.android.js
var React = require('react-native');
var SQLite = require('react-native-sqlite-storage')
...

Opening a database

Opening a database is a little different between iOS and Android. Whereas on Android the location of the database file is fixed, there are three choices of where the database file can be located on iOS. The ‘location’ parameter you provide to the openDatabase call indicates where you would like the file to be created. This parameter is neglected on Android.
SQLite.openDatabase("myDatabase.db", "1.0", "Demo", -1);

Importing a pre-populated database.
You can import an existing database into your application.You can choose your own location to populate the database in your application
If your folder is www and the database file is named the same as the dbName – testDB in this example

SQLite.openDatabase({name : "testDB", createFromLocation : 1}, okCallback,errorCallback);

Use this flow to openDatabase call if your folder is called data instead of www or your filename does not match the name of the DB. In this case, the database is named as testDB but the file is as mydbfile.

SQLite.openDatabase({name : "testDB", createFromLocation : "~data/mydbfile.sqlite"}, okCallback,errorCallback);

Use this flow to openDatabase call if your folder is not in the application bundle but in-app sandbox i.e. downloaded from some remote location.

SQLite.openDatabase({name : "testDB", createFromLocation : "/data/mydbfile.sqlite"}, okCallback,errorCallback);

Additional options for the pre-populated database file

You can provide additional instructions to sqlite-storage to handle your pre-populated database file. By default, the source file is copied over to the internal location which works in most cases but sometimes this is not an option particularly when the source DB file is large. In such situations, you can tell sqlite-storage you do not want to copy the file but rather use it in a read-only fashion via direct access.
SQLite.openDatabase({name : "testDB", readOnly: true, createFromLocation : "/data/mydbfile.sqlite"}, okCallback,errorCallback);

Note that in this case, the DB file will be open in read-only mode. You cannot delete a database that was open with the readOnly option. For Android, the read-only option works with pre-populated DB files located in the FilesDir directory because all other assets are never physically located on the file system but rather read directly from the app bundle.

Attaching another database

Sqlite3 provides the facility to attach another database to an existing database-instance, i.e. for making cross-database JOINs available. This functionality allows us to SELECT and JOIN tables over multiple databases with only one statement and only one database connection. To achieve this, you need to open both databases and to call the attach()-method of the destination (or master) -database to the other ones.

let dbMaster, dbSecond;
dbSecond = SQLite.openDatabase({name: 'second'},
(db) => {
dbMaster = SQLite.openDatabase({name: 'master'},
(db) => {
dbMaster.attach( "second", "second", () => console.log("Database attached successfully"), () => console.log("ERROR"))
},
(err) => console.log("Error on opening database 'master'", err)
);
},
(err) => console.log("Error on opening database 'second'", err)
);

The first argument of attaching () is the name of the database, which is used in SQLite.openDatabase(). The second argument is the alias, which is used to query on tables of the attached database.
The following statement should select data from the parent database and include the “child”-database within a simple SELECT/JOIN-statement:

SELECT * FROM user INNER JOIN second.subscriptions s ON s.user_id = user.id
To detach a database, just use the detach()-method:
dbMaster.detach( 'second', successCallback, errorCallback );

English is a commonly used language in almost all fields today. Having a certification in the English language can enhance your career aspects. StudySection offers both basic level and advanced level English Certification Exams to test and certify the English language skills.

Leave a Reply

Your email address will not be published. Required fields are marked *