在React Native中开始使用sqlite

React Native apps come with a simple user interface, code reusability, and allows for the production of stable apps. With React-Native being one of the most popular and ideal frameworks for creating cross-platform mobile applications, the vast majority of the developers and engineers depend on the structure of the framework to deliver high-performing local applications. Because of this, it’s often challenging for developers to choose the right technology stack (including the appropriate database for React Native). In this article we will be discussing SQLite as a local database for React-Native, and work on how to pre-populate data into the database so as to use it in the application.

React Native应用程序具有简单的用户界面,代码可重用性,并允许生产稳定的应用程序。 由于React-Native是用于创建跨平台移动应用程序的最受欢迎和理想的框架之一,因此绝大多数开发人员和工程师都依赖于框架的结构来交付高性能的本地应用程序。 因此,对于开发人员而言,选择正确的技术堆栈(包括适用于React Native的适当数据库)通常具有挑战性。 在本文中,我们将讨论SQLite作为React-Native的本地数据库,并研究如何将数据预填充到数据库中以便在应用程序中使用。

The word “lite” in SQLite describes it as being a lightweight library based database which requires minimal setup. SQLite can be coordinated with a versatile application, allowing us to get to the database in an easy, straightforward manner. It’s also helpful to note that SQLite was designed to provide local storage to mobile apps.

SQLite中的“ lite”一词将其描述为基于轻量级库的数据库,需要最少的设置。 SQLite可以与通用应用程序配合使用,使我们能够以简单,直接的方式访问数据库。 注意到SQLite旨在为移动应用程序提供本地存储也很有帮助。

The two main benefits of using SQLite database are:

使用SQLite数据库的两个主要好处是:

  1. It’s ACID-compliant (an acronym for atomicity, consistency, isolation, and durability)

    它符合ACID( 原子性一致性隔离 耐用 的首字母缩写)

  2. Its offline persistence (which means that it works even when the device is offline)

    它的离线持久性(这意味着即使设备离线也可以工作)

建立资料库 (Creating a database)

First, we need to create a database and store some data in it. https://sqliteonline.com/ can help in creating a SQLite database.

首先我们需要创建一个数据库并在其中存储一些数据。 https://sqliteonline.com/可以帮助创建SQLite数据库。

Create a new table and use the command- CREATE TABLE table_name (
column1 datatype,
column2 datatype,
column3 datatype,
….
);

For example-

例如-

CREATE TABLE Users(Title varchar(20),Age number); 

Now we need to insert values to this table structure:

现在我们需要向该表结构中插入值:

INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);

For example:

例如:

INSERT INTO Users(Title,Age)
VALUES ("Rohit" , 42);

Now your database is ready and you can download the user.db that you have created. For now, store the file in a temporary location.

现在您的数据库已准备就绪,您可以下载已创建的user.db。 现在,将文件存储在一个临时位置。

将数据库与react-native集成 (Integrating the database with react-native)

Step 1: After setting up your react native environment install the SQLite package

第1步:设置好响应本机环境后,安装SQLite软件包

npm install react-native-sqlite-storagereact-native link

Step 2:

第2步:

For iOS:

对于iOS:

open ./ios/podfilepod 'react-native-sqlite-storage', :path => '../node_modules/react-native-sqlite-storage'cd ./ios && pod install

For Android:

对于Android

  1. Open and modify android/settings.gradle file as follows:

    打开并修改android/settings.gradle文件,如下所示:

rootProject.name = 'react_native_sqlite_storage_exercise'
...
include ':react-native-sqlite-storage'
project(':react-native-sqlite-storage').projectDir = new
File(rootProject.projectDir, '../node_modules/react-native-sqlite- storage/src/android')
...include ':app'

2. Modify android/app/build.gradle file as follows:

2.修改android/app/build.gradle文件,如下所示:

...   
dependencies {
implementation fileTree(dir: "libs", include: ["*.jar"]) implementation"com.android.support:appcompatv7:${rootProject.ext.supportLibVersion}"
implementation "com.facebook.react:react-native:+"
...
implementation project(':react-native-sqlite-storage') \
}
...

3. Open and modify MainApplication.java file as below:

3.打开并修改MainApplication.java文件,如下所示:

...   
import org.pgsqlite.SQLitePluginPackage;
...
public class MainApplication extends Application implements ReactApplication {
...
...
@Override
protected List<ReactPackage> getPackages() {
return Arrays.<ReactPackage>asList(
...
new SQLitePluginPackage(),
...
new MainReactPackage()
);
}
}

Step 3: Adding the database file to the correct location

步骤3:将数据库文件添加到正确的位置

For iOS:

对于iOS:

Create ios/[project name]/www folder and copy the database on it.

创建ios/[project name]/www文件夹并在其上复制数据库。

For Android:

对于Android:

Create www folder in the main project directory and copy the database on it.

在主项目目录中创建www文件夹,然后在其上复制数据库。

Step 4-

第4步-

Create a constructor and add these lines of code:

创建一个构造函数并添加以下代码行:

constructor(props) {
    super(props);
    this.state={
      userList:[],
    }
    db = SQLite.openDatabase(
      {
        name: 'user.db',
        createFromLocation : 1,
      },
      this.success.bind(this),  //okCallback
      this.fail                // error callback
    );
    }

The constructor consists of four parts:

构造函数包括四个部分:

  1. The state — which is initially declared as an empty array (this will later be populated with data from the database).

    状态—最初声明为空数组(以后将用数据库中的数据填充该状态)。
  2. SQLite is imported and openDatabase function is called where the argument it takes is the name of the database and the location of the database.

    导入SQLite并调用openDatabase函数,该函数接受的参数是数据库的名称和数据库的位置。

  3. The success callback function ( which is called if there are no errors).

    成功回调函数(如果没有错误,则调用该函数)。
  4. The error callback function ( which is executed if there is an error).

    错误回调函数(如果有错误,则执行)。

Step 5-

第5步

Now we have to add the success and the fail call back functions:

现在,我们必须添加成功和失败回调函数:

success=()=>{
      db.transaction(tx => {
        tx.executeSql('SELECT * FROM user', [], (tx, results) => {  // sql query to get all table data and storing it in 'results' variable
          let data = results.rows.length;                          
          let users = [];    //creating empty array to store the rows of the sql table data
  
          for (let i = 0; i < results.rows.length; i++) {
            users.push(results.rows.item(i));                   //looping through each row in the table and storing it as object in the 'users' array
          }
  
           this.setState({ userList:users});         //setting the state(userlist) with users array which has all the table data
        });
      });
      // alert("ok")
    }
  
    fail=(error)=>{ 
      console.error(error) // logging out error if there is one
    }

In the success function, we declare a function db.transaction wherein the first argument we run the SQL query Select * from table_name (this selects all the rows in the SQL database). These rows are stored in a variable called “results”. Now we have to loop through each row of the “results” so that we can store data row by row in the array, thus we use the for loop. Now, after all the rows are pushed to the array, we use setState to update the state value.

在成功函数中,我们声明一个函数db.transaction,其中第一个参数运行SQL查询Select * from table_name(这将选择SQL数据库中的所有行)。 这些行存储在称为“结果”的变量中。 现在我们必须遍历“结果”的每一行,以便可以将数据逐行存储在数组中,因此我们使用了for循环。 现在,在将所有行都推送到数组之后,我们使用setState更新状态值。

In the fail function definition, we console.error the error so that debugging can be easier

在失败函数定义中,我们console.error错误,以便调试更容易

Step 6-

步骤6-

We create a render function and display the contents of the table in a scrollable view:

我们创建一个渲染函数,并在可滚动视图中显示表的内容:

<ScrollView>
        {
           this.state.userList.map(function(item, i){  //map through each element of array(each row of the sql table)
             return(
               <View key={i} style={styles.card}>   //we display the name and age of the user
                <Text>{item.Title}</Text>  
                <Text>{item.age}</Text>   
               </View>
             )
           })
         }    
</ScrollView>

We use Scrollview to make a scrollable view of the list of all items we stored in the database. Now, since the rows are stored as an array of objects in the userList variable, we have to map through each element of the array and print the title and the age of the person.

我们使用Scrollview来滚动查看存储在数据库中的所有项目的列表。 现在,由于这些行以对象数组的形式存储在userList变量中,因此我们必须映射该数组的每个元素并打印人员的标题和年龄。

结论 (Conclusion)

That’s it! In just six simple steps we have the basic setup of an SQLite database that is rendering its data to the front-end using React-Native. As discussed earlier, React-Native can be an incredibly helpful tool for developers and engineers, but knowing which technology stack is right for the task at hand can be a complicated process. I hope that this article has helped you work through this issue, and to evaluate whether SQLite can act as a worthy local database option for your next project! Thanks for reading and feel free to leave questions or feedback in the comments section.

而已! 仅用六个简单的步骤,我们就建立了一个SQLite数据库的基本设置,该数据库使用React-Native将其数据呈现​​到前端。 如前所述,React-Native对开发人员和工程师而言是非常有用的工具,但是要知道哪种技术堆栈适合当前任务可能是一个复杂的过程。 我希望本文能帮助您解决此问题,并评估SQLite是否可以充当下一个项目的重要本地数据库选项! 感谢您的阅读,并随时在评论部分中提出问题或反馈。

Click here to view the complete source code.

单击此处查看完整的源代码。

翻译自: https://codeburst.io/getting-started-with-sqlite-in-react-native-e25e361b8205

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值