Android之Sqlite的增删查操作

简介:

   今天写了个sqlite CRUD的操作实例,这里做个笔记。android的存储方式有很多有sharedpreferenced、file、xml、sqlite等。

   sqlite的介绍网络上实在是多,俺还是直接代码。对用户的注册情况进行CRUD操作。

1、首先创建个DBHelper继承SQLiteOpenHelper 

 

 
  1. package com.xzw.db.utils; 
  2.  
  3. import android.content.Context; 
  4. import android.database.sqlite.SQLiteDatabase; 
  5. import android.database.sqlite.SQLiteDatabase.CursorFactory; 
  6. import android.database.sqlite.SQLiteOpenHelper; 
  7.  
  8. /** 
  9.  * 该类是一个数据库的帮助类,用于创建数据库 
  10.  * @author xzw
  11.  * 
  12.  */ 
  13. public class DBHelper extends SQLiteOpenHelper { 
  14.      
  15.     private static final String TAG = "DBHelper"
  16.     private String dbName; 
  17.     private String tableName; 
  18.     private String createTableSql; 
  19.      
  20.     /** 
  21.      *  
  22.      * @param context  上下文 
  23.      * @param dbName   数据库名 
  24.      * @param version   数据库版本号 
  25.      * @param tableName  表名称 
  26.      * @param createTableSql  建表Sql 
  27.      */ 
  28.     public DBHelper(Context context, String dbName,int version,String tableName,String createTableSql) { 
  29.          
  30.         super(context, dbName, null, version);  
  31.         this.dbName = dbName; 
  32.         this.tableName = tableName; 
  33.         this.createTableSql = createTableSql; 
  34.     } 
  35.  
  36.     @Override 
  37.     public void onCreate(SQLiteDatabase db) { 
  38.         db.execSQL(createTableSql); 
  39.     } 
  40.  
  41.     @Override 
  42.     public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { 
  43.          String sql = "DROP TABLE IF EXISTS "+tableName; 
  44.          db.execSQL(sql); 
  45.          onCreate(db); 
  46.     } 
  47.  

2、创建User对象

 

 
  1. package com.xzw.db.bean; 
  2.  
  3. public class User { 
  4.     private Integer userid; 
  5.     private String userName; 
  6.     private String password; 
  7.     private String sex; 
  8.     private long regTime; 
  9.  
  10.     public User() { 
  11.     } 
  12.  
  13.     public User(String userName, String password, String sex, long regTime) { 
  14.  
  15.         this.userName = userName; 
  16.         this.password = password; 
  17.         this.sex = sex; 
  18.         this.regTime = regTime; 
  19.  
  20.     } 
  21.  
  22.     public User(Integer userid, String userName, String password, String sex, 
  23.             long regTime) { 
  24.         this.userid = userid; 
  25.         this.userName = userName; 
  26.         this.password = password; 
  27.         this.sex = sex; 
  28.         this.regTime = regTime; 
  29.     } 
  30.  
  31.     public Integer getUserid() { 
  32.         return userid; 
  33.     } 
  34.  
  35.     public void setUserid(Integer userid) { 
  36.         this.userid = userid; 
  37.     } 
  38.  
  39.     public String getUserName() { 
  40.         return userName; 
  41.     } 
  42.  
  43.     public void setUserName(String userName) { 
  44.         this.userName = userName; 
  45.     } 
  46.  
  47.     public String getPassword() { 
  48.         return password; 
  49.     } 
  50.  
  51.     public void setPassword(String password) { 
  52.         this.password = password; 
  53.     } 
  54.  
  55.     public String getSex() { 
  56.         return sex; 
  57.     } 
  58.  
  59.     public void setSex(String sex) { 
  60.         this.sex = sex; 
  61.     } 
  62.  
  63.     public long getRegTime() { 
  64.         return regTime; 
  65.     } 
  66.  
  67.     public void setRegTime(long regTime) { 
  68.         this.regTime = regTime; 
  69.     } 
  70.  
  71.     @Override 
  72.     public String toString() { 
  73.         // TODO Auto-generated method stub 
  74.         return "[User]userid = " + userid + " ,userName = " + userName 
  75.                 + ", password = " + password + "sex = " + sex + ",regTime = " 
  76.                 + regTime; 
  77.     } 
  78.  

3、创建UserStorage进行crud处理。

 

 
  1. package com.xzw.db.utils; 
  2.  
  3. import java.util.ArrayList; 
  4. import java.util.List; 
  5.  
  6. import com.xzw.db.bean.User; 
  7.  
  8. import android.content.ContentValues; 
  9. import android.content.Context; 
  10. import android.database.Cursor; 
  11. import android.database.sqlite.SQLiteDatabase; 
  12. import android.util.Log; 
  13.  
  14. public class UserStorage { 
  15.     private static final String TAG = "UserStorage"
  16.      
  17.     private static final String DB_NAME = "user_data.db"
  18.     public static final String TABLE_NAME = "user_data"
  19.     private static final int DB_VERSION = 1
  20.      
  21.     static final String COLUM_ID = "_id"
  22.     static final String COLUM_USER_NAME = "username"
  23.     static final String COLUM_PASSWORD = "password"
  24.     static final String COLUM_SEX = "sex"
  25.     static final String COLUM_REG_TIME = "reg_time"
  26.      
  27.     private String mCreateTableSql = "create table if not exists " + TABLE_NAME  
  28.             + "("+COLUM_ID+" integer primary key autoincrement," 
  29.             +COLUM_USER_NAME + " text not null," 
  30.             +COLUM_PASSWORD  + " text not null," 
  31.             +COLUM_SEX + " text," 
  32.             +COLUM_REG_TIME + " bigint not null" 
  33.             +")"
  34.      
  35.     private DBHelper dbHelper; 
  36.      
  37.     public UserStorage(Context context){ 
  38.         dbHelper = new DBHelper(context, DB_NAME, DB_VERSION, TABLE_NAME, mCreateTableSql); 
  39.     } 
  40.      
  41.     /** 
  42.      * 插入数据 
  43.      * @param cv 
  44.      * @return 
  45.      */ 
  46.     public long insert(ContentValues cv){ 
  47.         //以写的方式创建或打开数据库 
  48.         SQLiteDatabase db = dbHelper.getWritableDatabase(); 
  49.         long result = db.insert(TABLE_NAME, null, cv); 
  50.         db.close(); //操作完成记得关闭数据库 
  51.          
  52.         if(result > 0 ){ 
  53.             Log.i(TAG, "[Insert] success:" + result); 
  54.         }else
  55.             Log.e(TAG, "Failed to insert into " + TABLE_NAME); 
  56.         } 
  57.         return result; 
  58.          
  59.     } 
  60.     /** 
  61.      * 批量插入多条数据 
  62.      * @param cvs 
  63.      * @return 
  64.      */ 
  65.     public int insert(List<ContentValues> cvs){ 
  66.         int count = 0
  67.         SQLiteDatabase db = dbHelper.getWritableDatabase(); 
  68.          
  69.         for(ContentValues cv : cvs){ 
  70.             long id = insert(cv,db); 
  71.             count += id>0?1:0
  72.         } 
  73.         db.close(); 
  74.         return count; 
  75.     } 
  76.     /** 
  77.      * 插入数据 
  78.      * @param cv 
  79.      * @param db 
  80.      * @return 
  81.      */ 
  82.     private long insert(ContentValues cv,SQLiteDatabase db){ 
  83.         long result = db.insert(TABLE_NAME, null, cv); 
  84.          if(result > 0 ){ 
  85.             Log.i(TAG, "[Insert] success:" + result); 
  86.          }else
  87.             Log.e(TAG, "Failed to insert into " + TABLE_NAME); 
  88.          } 
  89.         return result; 
  90.     } 
  91.      /** 
  92.       * 根据id更新记录 
  93.       * @param cv 
  94.       * @param id 
  95.       * @return 
  96.       */ 
  97.     public int updateUserById(ContentValues cv,String id){ 
  98.         SQLiteDatabase db = dbHelper.getWritableDatabase(); 
  99.         int result = db.update(TABLE_NAME, cv, "_id=?"new String[]{id}); 
  100.         db.close(); 
  101.          
  102.          if(result > 0 ){ 
  103.             Log.i(TAG, "[Update] success:" + result); 
  104.           }else
  105.             Log.e(TAG, "Failed to upate " + TABLE_NAME); 
  106.           } 
  107.         return result; 
  108.          
  109.     } 
  110.      
  111.     /** 
  112.      * 获取所有列 
  113.      * @return 
  114.      */ 
  115.     public String[] getColumns(){ 
  116.         return new String[]{COLUM_ID,COLUM_USER_NAME,COLUM_PASSWORD,COLUM_SEX,COLUM_REG_TIME}; 
  117.     } 
  118.      
  119.     public List<User> getAllUser(){ 
  120.         List<User> users = new ArrayList<User>(); 
  121.         SQLiteDatabase db = dbHelper.getReadableDatabase(); 
  122.         Cursor cursor = db.query(TABLE_NAME, getColumns(), nullnullnullnull, COLUM_ID); 
  123.         while(cursor.moveToNext()){ 
  124.              
  125.             User user = fillUser(cursor); 
  126.             //添加user到集合中  
  127.             users.add(user); 
  128.         } 
  129.         cursor.close(); //游标使用完成后记得关闭 
  130.         db.close(); 
  131.          
  132.         return users; 
  133.          
  134.     } 
  135.  
  136.     private User fillUser(Cursor cursor) { 
  137.         User user = new User(); 
  138.       
  139.         user.setUserid(cursor.getInt(cursor.getColumnIndex(COLUM_ID))); 
  140.         user.setUserName(getValueByColumnName(cursor,COLUM_USER_NAME)); 
  141.         user.setPassword(getValueByColumnName(cursor,COLUM_PASSWORD)); 
  142.         user.setSex(getValueByColumnName(cursor,COLUM_SEX)); 
  143.         user.setRegTime(cursor.getLong(cursor.getColumnIndex(COLUM_REG_TIME))); 
  144.         return user; 
  145.     } 
  146.      
  147.     /** 
  148.      * 根据ID获取数据 
  149.      * @param id 
  150.      * @return 
  151.      */ 
  152.     public User getUserById(String id){ 
  153.       
  154.         SQLiteDatabase db = dbHelper.getReadableDatabase(); 
  155.          
  156.         String where = "_id=?"
  157.         String[] selectionArgs = new String[]{id}; 
  158.          
  159.         Cursor cursor = db.query(TABLE_NAME, getColumns(), where, selectionArgs, nullnullnull); 
  160.         User user = null
  161.          if(cursor.moveToFirst()){ 
  162.              user = fillUser(cursor); 
  163.          } 
  164.         cursor.close(); //游标使用完成后记得关闭 
  165.         db.close(); 
  166.          
  167.         return user; 
  168.          
  169.     } 
  170.      
  171.     /** 
  172.      * 根据id删除记录 
  173.      * @param id 
  174.      * @return 
  175.      */ 
  176.     public int deleteById(String id){ 
  177.          
  178.         SQLiteDatabase db = dbHelper.getWritableDatabase(); 
  179.         int result = db.delete(TABLE_NAME, "_id=?"new String[]{id}); 
  180.         db.close(); 
  181.          
  182.            
  183.         if(result > 0 ){ 
  184.             Log.i(TAG, "[Delete] success:" + result); 
  185.         }else
  186.             Log.e(TAG, "Failed to delete from " + TABLE_NAME); 
  187.         } 
  188.          
  189.         return result; 
  190.     } 
  191.      
  192.     //获取字段值 
  193.     private String getValueByColumnName(Cursor cursor,String columnName){ 
  194.         return cursor.getString(cursor.getColumnIndex(columnName)); 
  195.     } 
  196.      
  197.     /** 
  198.      * 清空表数据 
  199.      * @param id 
  200.      * @return 
  201.      */ 
  202.     public void clear(){ 
  203.         SQLiteDatabase db = dbHelper.getWritableDatabase(); 
  204.         db.delete(TABLE_NAME, nullnull); 
  205.         db.close(); 
  206.     } 

4、编写UserService进行业务处理。

 

 
  1. package com.xzw.db.utils; 
  2.  
  3. import java.util.ArrayList; 
  4. import java.util.List; 
  5.  
  6. import android.content.ContentValues; 
  7. import android.content.Context; 
  8. import android.os.storage.StorageManager; 
  9.  
  10. import com.xzw.db.bean.User; 
  11.  
  12. public class UserService { 
  13.      
  14.     private UserStorage userStorage; 
  15.      
  16.     public UserService(Context context){ 
  17.         userStorage = new UserStorage(context); 
  18.     } 
  19.      
  20.     /** 
  21.      * 保存用户 
  22.      *  
  23.      * @param user 
  24.      * @return 
  25.      */ 
  26.     public long saveUser(User user){ 
  27.          
  28.         ContentValues cv = fillContentValues(user); 
  29.         long count = userStorage.insert(cv); 
  30.          
  31.         return count; 
  32.     } 
  33.      
  34.     /** 
  35.      * 批量保存用户 
  36.      * @param users 
  37.      * @return 
  38.      */ 
  39.     public long saveUser(List<User> users){ 
  40.      
  41.         List<ContentValues> contentValues = new ArrayList<ContentValues>(); 
  42.         for(User user:users){ 
  43.             ContentValues cv = fillContentValues(user); 
  44.             contentValues.add(cv); 
  45.         } 
  46.         long count = userStorage.insert(contentValues); 
  47.          
  48.         return count; 
  49.     } 
  50.      
  51.     /** 
  52.      * 根据id修改数据 
  53.      * @param user 
  54.      * @return 
  55.      */ 
  56.     public int updateUserById(User user){ 
  57.         ContentValues contentValues = fillContentValues(user); 
  58.       
  59.         return userStorage.updateUserById(contentValues, user.getUserid().toString()); 
  60.     } 
  61.      
  62.     /** 
  63.      * 获取所有用户信息 
  64.      * @return 
  65.      */ 
  66.     public List<User> getAllUser(){ 
  67.         return userStorage.getAllUser(); 
  68.     } 
  69.      
  70.     /** 
  71.      * 根据id获取用户信息 
  72.      * @param id 
  73.      * @return 
  74.      */ 
  75.     public User getUserById(String id){ 
  76.         return userStorage.getUserById(id); 
  77.     } 
  78.      
  79.     /** 
  80.      * 根据id删除数据 
  81.      * @param id 
  82.      * @return 
  83.      */ 
  84.     public int deleteById(String id){ 
  85.       return userStorage.deleteById(id); 
  86.   } 
  87.     /** 
  88.      * 删除所有数据 
  89.      */ 
  90.     public void deleteAll(){ 
  91.           userStorage.clear(); 
  92.     } 
  93.      
  94.     /** 
  95.      * 填充数据 
  96.      * @param user 
  97.      * @return 
  98.      */ 
  99.     private ContentValues fillContentValues(User user) { 
  100.         //以下代码比较多地方会用带,故将其抽象成为方法。也是一种优化手段 
  101.         ContentValues cv = new ContentValues();  
  102.         cv.put(UserStorage.COLUM_USER_NAME, user.getUserName()); 
  103.         cv.put(UserStorage.COLUM_PASSWORD, user.getPassword()); 
  104.         cv.put(UserStorage.COLUM_SEX, user.getSex()); 
  105.         cv.put(UserStorage.COLUM_REG_TIME, user.getRegTime()); 
  106.         return cv; 
  107.     } 

以上是整个业务流程了。现在使用AndroidTestCase进行测试

创建TestUser继承AndroidTestCase

 

 
  1. package com.xzw.db; 
  2.  
  3. import java.util.ArrayList; 
  4. import java.util.List; 
  5.  
  6. import com.xzw.db.bean.User; 
  7. import com.xzw.db.utils.UserService; 
  8. import com.xzw.db.utils.UserStorage; 
  9.  
  10. import android.test.AndroidTestCase; 
  11. import android.util.Log; 
  12.  
  13. public class TestUser extends AndroidTestCase { 
  14.      
  15.      private static final String TAG = "TestUser"
  16.       
  17.     /** 
  18.      * 测试添加用户 
  19.      */ 
  20.     public void testSave(){ 
  21.         UserService userService = new UserService(this.getContext()); 
  22.         User user = new User("xzw""123456""男", System.currentTimeMillis()); 
  23.         userService.saveUser(user); 
  24.     } 
  25.      
  26.     /** 
  27.      * 测试批量添加用户 
  28.      */ 
  29.     public void testBatchSave(){ 
  30.         UserService userService = new UserService(this.getContext()); 
  31.         List<User> users = new ArrayList<User>(); 
  32.          
  33.         for(int i=0;i<10;i++){ 
  34.             User user = new User("hh-"+i, "123456", (i%2==0)?"男":"女", System.currentTimeMillis()); 
  35.             users.add(user); 
  36.         } 
  37.          
  38.         userService.saveUser(users); 
  39.     } 
  40.      
  41.     public void testGetAllUser(){ 
  42.         UserService userService = new UserService(this.getContext()); 
  43.         List<User> users =userService.getAllUser(); 
  44.         for(User user : users){ 
  45.             Log.i(TAG, user.toString()); 
  46.         } 
  47.     } 
  48.      
  49.     public void testGetUserById(){ 
  50.         UserService userService = new UserService(this.getContext()); 
  51.         User user =userService.getUserById("2"); 
  52.         Log.i(TAG, user.toString()); 
  53.       
  54.     } 
  55.      
  56.     public void testUpdateUser(){ 
  57.         UserService userService = new UserService(this.getContext()); 
  58.         User user = userService.getUserById("2"); 
  59.         user.setUserName("测试用户"); 
  60.         userService.updateUserById(user); 
  61.     } 
  62.      
  63.     public void testDeleteById(){ 
  64.         UserService userService = new UserService(this.getContext()); 
  65.         userService.deleteById("1"); 
  66.          
  67.     } 

代码全部编写完毕,运行前需要在AndroidManifest.xml文件添加

 

 
  1. <manifest xmlns:android="http://schemas.android.com/apk/res/android" 
  2.     package="com.xzw.db" 
  3.     android:versionCode="1" 
  4.     android:versionName="1.0" > 
  5.  
  6.     <uses-sdk 
  7.         android:minSdkVersion="8" 
  8.         android:targetSdkVersion="15" /> 
  9.  
  10.     <application 
  11.         android:icon="@drawable/ic_launcher" 
  12.         android:label="@string/app_name" 
  13.         android:theme="@style/AppTheme" > 
  14. <!--添加测试-->
  15.           <uses-library android:name="android.test.runner"/> 
  16.         <activity 
  17.             android:name=".MainActivity" 
  18.             android:label="@string/title_activity_main" > 
  19.             <intent-filter> 
  20.                 <action android:name="android.intent.action.MAIN" /> 
  21.  
  22.                 <category android:name="android.intent.category.LAUNCHER" /> 
  23.             </intent-filter> 
  24.         </activity> 
  25.     </application> 
  26. <!--添加测试目标包-->
  27. <instrumentation android:name="android.test.InstrumentationTestRunner" 
  28.         android:targetPackage="com.xzw.db" android:label="Tests for My App"/> 
  29. </manifest> 

以上就是整个sqlite crud的操作了。

查询所有用户信息:

 

根据id进行查询。

 

update后查询的结果。

 

以上就是完整的过程了。

 


本文转自xuzw13 51CTO博客,原文链接:http://blog.51cto.com/xuzhiwei/1054965,如需转载请自行联系原作者

相关文章
|
19天前
|
Java 数据库 Android开发
【专栏】Kotlin在Android开发中的多线程优化,包括线程池、协程的使用,任务分解、避免阻塞操作以及资源管理
【4月更文挑战第27天】本文探讨了Kotlin在Android开发中的多线程优化,包括线程池、协程的使用,任务分解、避免阻塞操作以及资源管理。通过案例分析展示了网络请求、图像处理和数据库操作的优化实践。同时,文章指出并发编程的挑战,如性能评估、调试及兼容性问题,并强调了多线程优化对提升应用性能的重要性。开发者应持续学习和探索新的优化策略,以适应移动应用市场的竞争需求。
|
19天前
|
Java Android开发
Android系统 获取用户最后操作时间回调实现和原理分析
Android系统 获取用户最后操作时间回调实现和原理分析
37 0
|
19天前
|
开发框架 前端开发 .NET
七天.NET 8操作SQLite入门到实战 - (1)第七天BootstrapBlazor UI组件库引入
七天.NET 8操作SQLite入门到实战 - (1)第七天BootstrapBlazor UI组件库引入
|
19天前
|
存储 数据库连接 数据库
Android数据存储:解释SQLite数据库在Android中的使用。
Android数据存储:解释SQLite数据库在Android中的使用。
48 0
|
19天前
|
Linux Android开发
测试程序之提供ioctl函数应用操作GPIO适用于Linux/Android
测试程序之提供ioctl函数应用操作GPIO适用于Linux/Android
18 0
|
19天前
|
XML Java API
Android 浅度解析:系统框架层修改,编译,推送相关操作
Android 浅度解析:系统框架层修改,编译,推送相关操作
37 0
|
19天前
|
Android开发
[Android]视图的控触操作-MotionEvent
[Android]视图的控触操作-MotionEvent
37 0
|
19天前
|
算法 Java 数据安全/隐私保护
Android App开发之利用JNI实现加密和解密操作实战(附源码 简单易懂)
Android App开发之利用JNI实现加密和解密操作实战(附源码 简单易懂)
100 0
|
19天前
|
XML 数据库 数据安全/隐私保护
Android App规范处理中版本设置、发布模式、给数据集SQLite加密的讲解及使用(附源码 超详细必看)
Android App规范处理中版本设置、发布模式、给数据集SQLite加密的讲解及使用(附源码 超详细必看)
49 0
|
19天前
|
SQL 数据库 数据安全/隐私保护
Android Studio App开发中数据库SQLite的解析及实战使用(包括创建数据库,增删改查,记住密码等 附源码必看)
Android Studio App开发中数据库SQLite的解析及实战使用(包括创建数据库,增删改查,记住密码等 附源码必看)
180 0