Home > Web Front-end > JS Tutorial > Detailed explanation of examples of using Sqlite database in React Native

Detailed explanation of examples of using Sqlite database in React Native

零下一度
Release: 2017-06-24 14:35:13
Original
3344 people have browsed it
Projects created using Sqllite may be created in different environments. For example, projects created using Expo may be different from this one! But the specific ideas are the same. I hope this article can help everyone!

##1. Installation

The command line enters the root directory of the ReactNative project and executes

##npm install React-native-sqlite-storage --save

2. Make global Gradle settingsEdit the android/settings.gradle file and add the following content
include ':react-native-sqlite-storage'
project(':react-native-sqlite-storage').projectDir = new File(rootProject.projectDir, '../ node_modules/react-native-sqlite-storage/src/android')
3. Modify the android/app/build.gradle file

Add compile project(':react-native-sqlite-storage')


4. Edit the MainApplication.Java file, Register the sqlite module in MainActivitiy.java

##import org.pgsqlite.SQLitePluginPackage;


[java]
view plain copy
    @ Override
  1. ##protected List getPackages() {
  2. ##return Arrays.< ;ReactPackage>asList(

  3. ##                                                                           ,

  4. ##                                                                                                                                                                                                                                                                                        since
  5. ## }

  6. Screenshot below:

  7. 5. Use

  8. # to write the sqlite.js file and introduce the component import SQLiteStorage from 'react-native- sqlite-storage';

Pay attention to each printing exception, otherwise you may not see what went wrong
[javascript]
view plain copy

  1. import React,{Component} from 'react';

  2. import{

  3. ## ToastAndroid,

  4. } from

    'react-native';

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

  6. ##SQLiteStorage.DEBUG(
  7. true);

  8. ##var database_name =
  9. "test.db";

    //Database file

  10. var database_version =
  11. "1.0";

    //Version number

  12. var database_displayname =
  13. "MySQLite";

    ##var database_size = -1;
  14. //-1 It should mean unlimited
  15. ##var db;

  16. export

    default
  17. class SQLite
  18. extends Component{

    ## componentWillUnmount(){

  19. if(db){

  20. this._successCB('close');

  21. db.close();

    ## }
  22. else {
  23. ## console. log(
  24. "SQLiteStorage not open");

    ## }
  25. }

  26. open(){

  27. db = SQLiteStorage.openDatabase(

  28. database_name,

  29. database_version,

  30. ## database_displayname,
  31. ## database_size,
  32. ()=>{
  33.                                                                                                                                           
  34. ##                         (err)=>

  35. });

  36. return db; ## }

  37. createTable(){

  38. if (!db) {
  39.       this.open();

  40. ##                                                                                                    

  41. ## db.transaction((tx)=> {
  42. tx.executeSql(

    'CREATE TABLE IF NOT EXISTS USER(' +
  43. ##                                                                                                    '+
  44. ##                                                                                                              
  45.                                                                                                                                                                   #                                                                                                                                                                                                                    , , ,                                 ##            

    this._successCB(
  46. 'executeSql');    
  47. ##                                                                                                                      
  48.                   

    this._errorCB('executeSql', err);

    }, (err)=> {
  49. //All transactions should have error callback methods and print exception information in the method, otherwise you may not know what went wrong.
  50. ##         
  51. this._errorCB(

    'transaction', err);

  52. }, ()=> {
  53. this._successCB(

    'transaction');

  54. })
  55. ## }
  56. deleteData(){

  57. if (!db) {

    ##this.open();
  58. ## }
  59. db.transaction((tx)=>{

    tx.executeSql(
  60. 'delete from user',[],()=> ;{
  61. # });
  62. });
  63. }

  64. dropTable(){

    ## db.transaction((tx)=>{
  65. tx.executeSql(
  66. 'drop table user',[],()=>{
  67. });
  68. },(err)=>{
  69. this ._errorCB(
  70. 'transaction', err);

  71. ## },()=>{

  72.     

    this._successCB(
  73. 'transaction'); 
  74. ##                                                      

    insertUserData(userData){
  75. let len ​​= userData.length;
  76. if (!db) {
  77. ##this.open();

    ## }

  78.    

    this.createTable();  

  79.       this.deleteData();    

  80. db.transaction((tx)=>{

  81.                                                                                                                                                                                                                                                                   

    # Let age = user.age;
  82. ## let sex = user.sex;

  83.         let phone = user.phone;  

  84.         let email = user.email;  

  85.         let qq = user.qq;  

  86.         let sql = "INSERT INTO user(name,age,sex,phone,email,qq)"+  

  87.         "values(?,?,?,?,?,?)";  

  88.         tx.executeSql(sql,[name,age,sex,phone,email,qq],()=>{  

  89.           },(err)=>{  

  90.             console.log(err);  

  91.           }  

  92.         );  

  93.       }  

  94.     },(error)=>{  

  95.       this._errorCB('transaction', error);  

  96.       ToastAndroid.show("数据插入失败",ToastAndroid.SHORT);  

  97.     },()=>{  

  98.       this._successCB('transaction insert data');  

  99.       ToastAndroid.show("成功插入 "+len+" 条用户数据",ToastAndroid.SHORT);  

  100.     });  

  101.   }  

  102.   close(){  

  103.       if(db){  

  104.           this._successCB('close');  

  105.           db.close();  

  106.       }else {  

  107.           console.log("SQLiteStorage not open");  

  108.       }  

  109.       db = null;  

  110.   }  

  111.   _successCB(name){  

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

  113.   }  

  114.   _errorCB(name, err){  

  115.     console.log("SQLiteStorage "+name);  

  116.     console.log(err);  

  117.   }  

  118.     render(){  

  119.         return null;  

  120.     }  

  121. };  

'react';

  • ##import {

  • AppRegistry,

  • Text,

  • View,

  • Navigator,

  • StyleSheet,

  • ##} from
  • 'react-native';

  • import SQLite from

    './sqlite';

  • var sqLite =

    new SQLite();

  • ##var db;
  • class App
  • extends Component{

    ## compennenetDidUnmount(){

  • sqLite.close( );

  • }

  • componentWillMount(){

  • //Open the database
  • ##     if(!db){  

  •       db = sqLite.open();  

  • }  

  •  

    //Create table  

  •   sqLite.createTable();

  • //Delete data

  • ## sqLite.deleteData();

  • //Simulating a piece of data

  • var userData = [];

  • ##var user = {};

  • user.name =

    "张三";

  • ## user.age =
  • "28";

  • user.sex =
  • "Male";

    ## user.phone =
  • "18900001111";
  • user.email =
  • "2343242@qq.com";
  • user.qq =
  • "111222";
  • ## userData.push(user);

  • //Insert data

  • ## sqLite.insertUserData(userData);

  • //Query

  • ## db.transaction((tx)=>{
  • tx.executeSql(
  • "select * from user ", [],(tx,results)=>{

  • ##var len = results.rows.length;
  •                                                      i);

    ##          
  • //Generally after the data is found, you may need to setState operation to re-render the page
  •        alert(
  • "Name: "+u.name+
  • ", Age: "+u.age+

    ", Phone: "+u.phone);

  • } }

  • ## });
  • },(error)=>{

    //Print exception information
  • ## Console.log(error);

  •     });  

  •   }  

  •     render(){  

  •         return null;  

  •     }  

 

The above is the detailed content of Detailed explanation of examples of using Sqlite database in React Native. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template