React Native 中怎样行使Sqlite数据库。Android 数据库SQLite的以简易Demo

动Sqllite可能因此不同的环境创建出来的档次,比如说:用Expo创建的即可能与这个不均等!但是现实思路都是同样的,希望这篇稿子可以协助及大家!

在手机支付中SQLite的运用demo


简单的bean类

1.安装

Java代码  澳门新葡亰 1

命执行上到ReactNative项目根本目录下执行

  1. package com.easyway.android.sql;  
  2. /** 
  3.  * 普通JavaBean 
  4.  * @author longgangbai 
  5.  * 
  6.  */  
  7. public class CityBean {  
  8.     public static final String ID = “_id”;  
  9.     public static final String CITY = “city”;  
  10.     public static final String CODE = “code”;  
  11.       
  12.     private String id;  
  13.     private String city;  
  14.     private String code;  
  15.       
  16.     public String getId() {  
  17.         return id;  
  18.     }  
  19.     public void setId(String id) {  
  20.         this.id = id;  
  21.     }  
  22.     public String getCity() {  
  23.         return city;  
  24.     }  
  25.     public void setCity(String city) {  
  26.         this.city = city;  
  27.     }  
  28.     public String getCode() {  
  29.         return code;  
  30.     }  
  31.     public void setCode(String code) {  
  32.         this.code = code;  
  33.     }  
  34.   
  35. }  

npm install
React-native-sqlite-storage
–save

 

 

 

2.拓展全局Gradle设置

界面展现类:

编制 android/settings.gradle文件,添加以下内容

Java代码  澳门新葡亰 2

include ‘:react-native-sqlite-storage’

  1. package com.easyway.android.sql;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.List;  
  5.   
  6. import android.app.Activity;  
  7. import android.content.ContentValues;  
  8. import android.database.Cursor;  
  9. import android.database.sqlite.SQLiteDatabase;  
  10. import android.os.Bundle;  
  11. import android.view.View;  
  12. import android.view.ViewGroup;  
  13. import android.widget.AdapterView;  
  14. import android.widget.BaseAdapter;  
  15. import android.widget.Button;  
  16. import android.widget.EditText;  
  17. import android.widget.ListView;  
  18. import android.widget.TextView;  
  19.   
  20. /** 
  21.  *  
  22.  *  
  23.  * 本例实现SQLite数据库增加、删除、修改、模糊查询操作。这里不是极端好的实现方式, 
  24.  * 如想研究SQL如何封装,请详细查看SQLiteDatebase类. 
  25.  * 查看SQL语句:String sql = SQLiteQueryBuilder.buildQueryString(); 
  26.  *  
  27.  *  
  28.  * @author  longgangbai 
  29.  */  
  30. public class AndroidSQL extends Activity {  
  31.     private static String DB_NAME = “mycity.db”;  
  32.     private static int DB_VERSION = 1;  
  33.     private static int POSTION;  
  34.     private ListView listview;  
  35.     private Cursor cursor;  
  36.     private SQLiteDatabase db;  
  37.     private SQLiteHelper dbHelper;  
  38.     private ListAdapter listAdapter;  
  39.       
  40.     private EditText etCity;  
  41.     private EditText etCode;  
  42.     private Button bt_add;  
  43.     private Button bt_modify;  
  44.     private Button bt_query;  
  45.       
  46.     private List<CityBean> cityList = new ArrayList<CityBean>();  
  47.     /** Called when the activity is first created. */  
  48.     @Override  
  49.     public void onCreate(Bundle savedInstanceState) {  
  50.         super.onCreate(savedInstanceState);  
  51.         setContentView(R.layout.main);  
  52.           
  53.         etCity = (EditText) findViewById(R.id.etCity);  
  54.         etCode = (EditText) findViewById(R.id.etCode);  
  55.         bt_add = (Button) findViewById(R.id.bt_add);  
  56.         bt_modify = (Button) findViewById(R.id.bt_modify);  
  57.         bt_query = (Button) findViewById(R.id.bt_query);  
  58.           
  59.         try{  
  60.             /* 初始化并创数量库 */  
  61.             dbHelper = new SQLiteHelper(this, DB_NAME, null, DB_VERSION);  
  62.             /* 创建表 */  
  63.             db = dbHelper.getWritableDatabase();    //调用SQLiteHelper.OnCreate()           
  64.             /* 查询表,得到cursor对象 */  
  65.             cursor = db.query(SQLiteHelper.TB_NAME, null, null, null, null, null, CityBean.CODE + ” DESC”);  
  66.             cursor.moveToFirst();  
  67.             while(!cursor.isAfterLast() && (cursor.getString(1) != null)){      
  68.                 CityBean city = new CityBean();  
  69.                 city.setId(cursor.getString(0));  
  70.                 city.setCity(cursor.getString(1));  
  71.                 city.setCode(cursor.getString(2));  
  72.                 cityList.add(city);  
  73.                 cursor.moveToNext();  
  74.             }  
  75.         }catch(IllegalArgumentException e){  
  76.             //当用SimpleCursorAdapter装载数据时,表ID列必须是_id,否则报错column ‘_id’ does not exist  
  77.             e.printStackTrace();  
  78.             //当版本更改时会调用SQLiteHelper.onUpgrade()方法重建表 注:表以前数据以遗失  
  79.             ++ DB_VERSION;  
  80.             dbHelper.onUpgrade(db, –DB_VERSION, DB_VERSION);  
  81. //          dbHelper.updateColumn(db, SQLiteHelper.ID, “_”+SQLiteHelper.ID, “integer”);  
  82.         }  
  83.         listview = (ListView)findViewById(R.id.listView);  
  84.         listAdapter = new ListAdapter();  
  85.         listview.setAdapter(listAdapter);  
  86.         listview.setOnItemClickListener(new ListView.OnItemClickListener(){  
  87.             @Override  
  88.             public void onItemClick(AdapterView<?> parent, View view, int postion,  
  89.                     long arg3) {  
  90.                 setSelectedValues(postion);  
  91.             }             
  92.         });  
  93.           
  94.         /* 插入表数据并ListView显示更新 */  
  95.         bt_add.setOnClickListener(new Button.OnClickListener(){  
  96.             @Override  
  97.             public void onClick(View arg0) {  
  98.                 if(etCity.getText().length() > 1 && etCode.getText().length() >1){  
  99.                     ContentValues values = new ContentValues();  
  100.                     values.put(CityBean.CITY, etCity.getText().toString().trim());  
  101.                     values.put(CityBean.CODE, etCode.getText().toString().trim());  
  102.                     //插入数据 用ContentValues对象为就算HashMap操作,并回到ID号  
  103.                     Long cityID = db.insert(SQLiteHelper.TB_NAME, CityBean.ID, values);  
  104.                     CityBean city = new CityBean();  
  105.                     city.setId(“”+cityID);  
  106.                     city.setCity(etCity.getText().toString().trim());  
  107.                     city.setCode(etCode.getText().toString().trim());  
  108.                     cityList.add(city);  
  109.                     listview.setAdapter(new ListAdapter());  
  110.                     resetForm();  
  111.                 }  
  112.             }  
  113.         });  
  114.           
  115.         /* 查询表,模糊条件查询 */  
  116.         bt_query.setOnClickListener(new Button.OnClickListener(){  
  117.             @Override  
  118.             public void onClick(View view) {  
  119.                 cityList.removeAll(cityList);  
  120.                 String sql = null;  
  121.                 String sqlCity = etCity.getText().length() > 0 ? CityBean.CITY + ” like ‘%” + etCity.getText().toString().trim() + “%'” : “”;                  
  122.                 String sqlCode = etCode.getText().length() > 0 ? CityBean.CITY + ” like ‘%” + etCity.getText().toString().trim() + “%'” : “”;  
  123.                 if( (!””.equals(sqlCity)) && (!””.equals(sqlCode)) ){  
  124.                     sql = sqlCity + ” and” + sqlCode;  
  125.                 }else if(!””.equals(sqlCity)){  
  126.                     sql = sqlCity;  
  127.                 }else if(!””.equals(sqlCode)){  
  128.                     sql = sqlCode;  
  129.                 }  
  130.                 cursor = db.query(true, SQLiteHelper.TB_NAME,   
  131.                         new String[]{CityBean.ID, CityBean.CITY, CityBean.CODE},   
  132.                         sql,   
  133.                         null, null, null, null, null);  
  134.                 cursor.moveToFirst();  
  135.                 while(!cursor.isAfterLast() && (cursor.getString(1) != null)){    
  136.                     CityBean city = new CityBean();  
  137.                     city.setId(cursor.getString(0));  
  138.                     city.setCity(cursor.getString(1));  
  139.                     city.setCode(cursor.getString(2));  
  140.                     cityList.add(city);  
  141.                     cursor.moveToNext();  
  142.                 }  
  143.                 listview.setAdapter(new ListAdapter());  
  144.                 resetForm();  
  145.             }  
  146.         });  
  147.           
  148.         /* 修改表数据 */  
  149.         bt_modify.setOnClickListener(new Button.OnClickListener(){  
  150.             @Override  
  151.             public void onClick(View arg0) {  
  152.                 ContentValues values = new ContentValues();  
  153.                 values.put(CityBean.CITY, etCity.getText().toString().trim());  
  154.                 values.put(CityBean.CODE, etCode.getText().toString().trim());  
  155.                 db.update(SQLiteHelper.TB_NAME, values, CityBean.ID + “=” + cityList.get(POSTION).getId(), null);  
  156.                 cityList.get(POSTION).setCity(etCity.getText().toString().trim());  
  157.                 cityList.get(POSTION).setCode(etCode.getText().toString().trim());  
  158.                 listview.setAdapter(new ListAdapter());  
  159.                 resetForm();  
  160.             }  
  161.         });  
  162.     }  
  163.       
  164.     /* 设置选中ListView的值 */  
  165.     public void setSelectedValues(int postion){  
  166.         POSTION = postion;  
  167.         etCity.setText(cityList.get(postion).getCity());  
  168.         etCode.setText(cityList.get(postion).getCode());  
  169.     }  
  170.       
  171.     /* 重值form */  
  172.     public void resetForm(){  
  173.         etCity.setText(“”);  
  174.         etCode.setText(“”);  
  175.     }  
  176.       
  177.     @Override  
  178.     protected void onDestroy() {  
  179.         db.delete(SQLiteHelper.TB_NAME, null, null);  
  180.         super.onDestroy();  
  181.     }  
  182.       
  183.     private class ListAdapter extends BaseAdapter{  
  184.         public ListAdapter(){  
  185.             super();  
  186.         }  
  187.         @Override  
  188.         public int getCount() {  
  189.             return cityList.size();  
  190.         }  
  191.   
  192.         @Override  
  193.         public Object getItem(int postion) {  
  194.             return postion;  
  195.         }  
  196.   
  197.         @Override  
  198.         public long getItemId(int postion) {  
  199.             return postion;  
  200.         }  
  201.   
  202.         @Override  
  203.         public View getView(final int postion, View view, ViewGroup parent) {  
  204.             view = getLayoutInflater().inflate(R.layout.listview, null);  
  205.             TextView tv = (TextView) view.findViewById(R.id.tvCity);  
  206.             tv.setText(“” + cityList.get(postion).getCity());  
  207.             TextView bu = (TextView) view.findViewById(R.id.btRemove);  
  208.             bu.setText(R.string.delete);  
  209.             bu.setId(Integer.parseInt(cityList.get(postion).getId()));  
  210.               
  211.             /* 删除表数据 */  
  212.             bu.setOnClickListener(new Button.OnClickListener(){  
  213.                 @Override  
  214.                 public void onClick(View view) {  
  215.                     try{  
  216.                         db.delete(SQLiteHelper.TB_NAME, CityBean.ID + “=” + view.getId(), null);  
  217.                         cityList.remove(postion);  
  218.                         listview.setAdapter(new ListAdapter());                       
  219.                     }catch(Exception e){  
  220.                         e.printStackTrace();  
  221.                     }  
  222.                 }  
  223.             });  
  224.             return view;  
  225.         }  
  226.     }  
  227. }  

project(‘:react-native-sqlite-storage’).projectDir = new
File(rootProject.projectDir,
‘../node_modules/react-native-sqlite-storage/src/android’)

 

3.修改android/app/build.gradle文件

 

dependencies 里面上加
 compile project(‘:react-native-sqlite-storage’)

 

澳门新葡亰 3

SQLite实现类:

4.编辑MainApplication.Java文件,在MainActivitiy.java中注册sqlite模块

Java代码  澳门新葡亰 4

import org.pgsqlite.SQLitePluginPackage;

  1. package com.easyway.android.sql;  
  2.   
  3. import android.content.Context;  
  4. import android.database.sqlite.SQLiteDatabase;  
  5. import android.database.sqlite.SQLiteOpenHelper;  
  6. import android.database.sqlite.SQLiteDatabase.CursorFactory;  
  7. /** 
  8.  * 实现对表的创立、更新、变更列名操作 
  9.  *  
  10.  * 在Android 中针对少量数的操作以SQLite操作实现相关职能效应 
  11.  * ,但是必须继续SQLiteOpenHelper,实现相关的效益。 
  12.  *   
  13.  *  
  14.  * @author longgangbai 
  15.  * 
  16.  */  
  17. public class SQLiteHelper extends SQLiteOpenHelper {  
  18.     public static final String TB_NAME = “citys”;  
  19.   
  20.     public SQLiteHelper(Context context, String name, CursorFactory factory,  
  21.             int version) {  
  22.         super(context, name, factory, version);  
  23.     }  
  24.       
  25.     /** 
  26.      * 创建新表 
  27.      */  
  28.     @Override  
  29.     public void onCreate(SQLiteDatabase db) {  
  30.         db.execSQL(“CREATE TABLE IF NOT EXISTS ” +  
  31.                 TB_NAME + “(” +  
  32.                 CityBean.ID + ” integer primary key,” +  
  33.                 CityBean.CITY + ” varchar,” +   
  34.                 CityBean.CODE + ” integer”+  
  35.                 “)”);  
  36.     }  
  37.       
  38.     /** 
  39.      * 当检测和前一模一样次创数据库版本不雷同不时,先去表再创建新表 
  40.      */  
  41.     @Override  
  42.     public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {  
  43.         db.execSQL(“DROP TABLE IF EXISTS ” + TB_NAME);  
  44.         onCreate(db);  
  45.     }  
  46.       
  47.     /** 
  48.      * 变更列名 
  49.      * @param db 
  50.      * @param oldColumn 
  51.      * @param newColumn 
  52.      * @param typeColumn 
  53.      */  
  54.     public void updateColumn(SQLiteDatabase db, String oldColumn, String newColumn, String typeColumn){  
  55.         try{  
  56.             db.execSQL(“ALTER TABLE ” +  
  57.                     TB_NAME + ” CHANGE ” +  
  58.                     oldColumn + ” “+ newColumn +  
  59.                     ” ” + typeColumn  
  60.             );  
  61.         }catch(Exception e){  
  62.             e.printStackTrace();  
  63.         }  
  64.     }  
  65.   
  66. }  

[java] view
plain
copy

 

  1. @Override  
  2.     protected List<ReactPackage> getPackages() {  
  3.       return Arrays.<ReactPackage>asList(  
  4.           new MainReactPackage(),  
  5.           new SQLitePluginPackage(),  
  6.           new BaiduMapPackage(getApplicationContext())  
  7.       );  
  8.     }  
  • AndroidSQL.rar
    (90.7 KB)

截图如下: 澳门新葡亰 5

5.使用

编写sqlite.js文件,引入组件
    import SQLiteStorage from
‘react-native-sqlite-storage’;

在意每一个打印好,不然可能看不到哪里错了

[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(true);  
  7. var database_name = “test.db”;//数据库文件  
  8. var database_version = “1.0”;//版本号  
  9. var database_displayname = “MySQLite”;  
  10. var database_size = -1;//-1应该是代表无比制  
  11. var db;  
  12. export default class  SQLite extends Component{  
  13.     componentWillUnmount(){  
  14.     if(db){  
  15.         this._successCB(‘close’);  
  16.         db.close();  
  17.     }else {  
  18.         console.log(“SQLiteStorage not open”);  
  19.     }  
  20.   }  
  21.   open(){  
  22.     db = SQLiteStorage.openDatabase(  
  23.       database_name,  
  24.       database_version,  
  25.       database_displayname,  
  26.       database_size,  
  27.       ()=>{  
  28.           this._successCB(‘open’);  
  29.       },  
  30.       (err)=>{  
  31.           this._errorCB(‘open’,err);  
  32.       });  
  33.     return db;  
  34.   }  
  35.   createTable(){  
  36.     if (!db) {  
  37.         this.open();  
  38.     }  
  39.     //创建用户表  
  40.     db.transaction((tx)=> {  
  41.       tx.executeSql(‘CREATE TABLE IF NOT EXISTS USER(‘ +  
  42.           ‘id INTEGER PRIMARY KEY  AUTOINCREMENT,’ +  
  43.           ‘name varchar,’+  
  44.           ‘age VARCHAR,’ +  
  45.           ‘sex VARCHAR,’ +  
  46.           ‘phone VARCHAR,’ +  
  47.           ’email VARCHAR,’ +  
  48.           ‘qq VARCHAR)’  
  49.           , [], ()=> {  
  50.               this._successCB(‘executeSql’);  
  51.           }, (err)=> {  
  52.               this._errorCB(‘executeSql’, err);  
  53.         });  
  54.     }, (err)=> {//所有的 transaction都该发生误的回调方法,在法中打印好信息,不然你恐怕无会见清楚何错了。  
  55.         this._errorCB(‘transaction’, err);  
  56.     }, ()=> {  
  57.         this._successCB(‘transaction’);  
  58.     })  
  59.     }  
  60.   deleteData(){  
  61.     if (!db) {  
  62.         this.open();  
  63.     }  
  64.     db.transaction((tx)=>{  
  65.       tx.executeSql(‘delete from user’,[],()=>{  
  66.   
  67.       });  
  68.     });  
  69.   }  
  70.   dropTable(){  
  71.     db.transaction((tx)=>{  
  72.       tx.executeSql(‘drop table user’,[],()=>{  
  73.   
  74.       });  
  75.     },(err)=>{  
  76.       this._errorCB(‘transaction’, err);  
  77.     },()=>{  
  78.       this._successCB(‘transaction’);  
  79.     });  
  80.   }  
  81.     insertUserData(userData){  
  82.     let len = userData.length;  
  83.     if (!db) {  
  84.         this.open();  
  85.     }  
  86.     this.createTable();  
  87.     this.deleteData();  
  88.     db.transaction((tx)=>{  
  89.        for(let i=0; i<len; i++){  
  90.         var user = userData[i];  
  91.         let name= user.name;  
  92.         let age = user.age;  
  93.         let sex = user.sex;  
  94.         let phone = user.phone;  
  95.         let email = user.email;  
  96.         let qq = user.qq;  
  97.         let sql = “INSERT INTO user(name,age,sex,phone,email,qq)”+  
  98.         “values(?,?,?,?,?,?)”;  
  99.         tx.executeSql(sql,[name,age,sex,phone,email,qq],()=>{  
  100.             
  101.           },(err)=>{  
  102.             console.log(err);  
  103.           }  
  104.         );  
  105.       }  
  106.     },(error)=>{  
  107.       this._errorCB(‘transaction’, error);  
  108.       ToastAndroid.show(“数据插入失败”,ToastAndroid.SHORT);  
  109.     },()=>{  
  110.       this._successCB(‘transaction insert data’);  
  111.       ToastAndroid.show(“成功插入 “+len+” 条用户数量”,ToastAndroid.SHORT);  
  112.     });  
  113.   }  
  114.   close(){  
  115.       if(db){  
  116.           this._successCB(‘close’);  
  117.           db.close();  
  118.       }else {  
  119.           console.log(“SQLiteStorage not open”);  
  120.       }  
  121.       db = null;  
  122.   }  
  123.   _successCB(name){  
  124.     console.log(“SQLiteStorage “+name+” success”);  
  125.   }  
  126.   _errorCB(name, err){  
  127.     console.log(“SQLiteStorage “+name);  
  128.     console.log(err);  
  129.   }  
  130.     render(){  
  131.         return null;  
  132.     }  
  133. };  

‘react’;  

  • import {  
  •   AppRegistry,  
  •   Text,  
  •   View,  
  •   Navigator,  
  •   StyleSheet,  
  • } from ‘react-native’;  
  • import SQLite from ‘./sqlite’;  
  • var sqLite = new SQLite();  
  • var db;  
  • class App extends Component{  
  •     compennetDidUnmount(){  
  •     sqLite.close();  
  •   }  
  •   componentWillMount(){  
  •     //开启数据库  
  •     if(!db){  
  •       db = sqLite.open();  
  •     }  
  •     //建表  
  •     sqLite.createTable();  
  •     //删除数据  
  •     sqLite.deleteData();  
  •     //模拟一条数澳门新葡亰  
  •     var userData = [];  
  •     var user = {};  
  •     user.name = “张三”;  
  •     user.age = “28”;  
  •     user.sex = “男”;  
  •     user.phone = “18900001111”;  
  •     user.email = “2343242@qq.com”;  
  •     user.qq = “111222”;  
  •     userData.push(user);  
  •     //插入数据  
  •     sqLite.insertUserData(userData);  
  •     //查询  
  •     db.transaction((tx)=>{  
  •       tx.executeSql(“select * from user”, [],(tx,results)=>{  
  •         var len = results.rows.length;  
  •         for(let i=0; i<len; i++){  
  •           var u = results.rows.item(i);  
  •           //一般在数据查出来之后,  可能而 setState操作,重新渲染页面  
  •           alert(“姓名:”+u.name+”,年龄:”+u.age+”,电话:”+u.phone);  
  •         }  
  •       });  
  •     },(error)=>{//打印好信息  
  •       console.log(error);  
  •     });  
  •   }  
  •     render(){  
  •         return null;  
  •     }  

 

笔者介绍:半路学IT,做开发3年,先下车于同一家共享单车店,做后台开发!

 

 我起来了一个公众号,欢迎各位有志同道合朋友,关注!不定期分享工作,和自己得故事!

 

澳门新葡亰 6

相关文章

Leave a Comment.