玩转android sqlLite---(附android DB的图行工具)

sqlLite就像个迷你数据库,配套的操作工具还不完善,操作起来不直观。不像oracle、mysql那样有图形化的操作工作。

 

偶然在网上发现一款操作sqlLite的图形化工具  ----  SQLiteSpy(后附上链接)。如下图:

 

 怎么样!嘿嘿,虽然功能还显简单,但对开发者来说,起码说看到比较直观的界面。

 

操作步骤很简单,首先导入sqlLite 的DB文件(即File Explorer   /data /data/   ),然后进行各种sql操作。

 

顺便写一下,我常用到的sqlLite操作类,对增删查改进行了简单的封装。

  1. import android.content.ContentValues;  
  2. import android.content.Context;  
  3. import android.database.Cursor;  
  4. import android.database.SQLException;  
  5. import android.database.sqlite.SQLiteDatabase;  
  6. import android.database.sqlite.SQLiteOpenHelper;  
  7.   
  8. public class DBHelper {  
  9.     static private DatabaseHelper mDbHelper;  
  10.     static private SQLiteDatabase mDb;  
  11.   
  12.     private static final String DATABASE_NAME = "zhyy.db";  
  13.       
  14.     private static final int DATABASE_VERSION = 1;  
  15.   
  16.     private final Context mCtx;  
  17.   
  18.     private static class DatabaseHelper extends SQLiteOpenHelper {  
  19.   
  20.         DatabaseHelper(Context context) {  
  21.             super(context, DATABASE_NAME, null, DATABASE_VERSION);  
  22.         }  
  23.   
  24.         @Override  
  25.         public void onCreate(SQLiteDatabase db) {  
  26.               
  27.         }  
  28.         @Override  
  29.         public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {  
  30.               
  31.         }  
  32.     }  
  33.   
  34.     public DBHelper(Context ctx) {  
  35.         this.mCtx = ctx;  
  36.     }  
  37.   
  38.     public DBHelper open() throws SQLException {  
  39.         mDbHelper = new DatabaseHelper(mCtx);  
  40.         mDb = mDbHelper.getWritableDatabase();  
  41.         return this;  
  42.     }  
  43.   
  44.     public void closeclose() {  
  45.           
  46.         mDb.close();  
  47.         mDbHelper.close();  
  48.     }  
  49.   
  50.     /** 
  51.      * 插入数据 
  52.      * 参数:tableName 表名 
  53.      * initialValues 要插入的列对应值 
  54.      *   */  
  55.     public long insert(String tableName,ContentValues initialValues) {  
  56.           
  57.         return mDb.insert(tableName, null, initialValues);  
  58.     }  
  59.   
  60.       
  61.     /** 
  62.      * 删除数据 
  63.      * 参数:tableName 表名 
  64.      * deleteCondition 删除的条件 
  65.      * deleteArgs 如果deleteCondition中有“?”号,将用此数组中的值替换 
  66.      *   */  
  67.     public boolean delete(String tableName,String deleteCondition,String[] deleteArgs) {  
  68.           
  69.         return mDb.delete(tableName, deleteCondition, deleteArgs) > 0;  
  70.     }  
  71.       
  72.       
  73.     /** 
  74.      * 更新数据 
  75.      * 参数:tableName 表名 
  76.      * initialValues 要更新的列 
  77.      * selection 更新的条件 
  78.      * selectArgs 如果selection中有“?”号,将用此数组中的值替换 
  79.      *   */  
  80.     public boolean update(String tableName,ContentValues initialValues,String selection,String[] selectArgs) {  
  81.         int returnValue = mDb.update(tableName, initialValues, selection, selectArgs);  
  82.           
  83.         return  returnValue > 0;  
  84.     }  
  85.   
  86.     /** 
  87.      * 取得一个列表 
  88.      * 参数:tableName 表名 
  89.      * columns 返回的列 
  90.      * selection 查询条件 
  91.      * selectArgs 如果selection中有“?”号,将用此数组中的值替换 
  92.      *   */  
  93.     public Cursor findList(String tableName,String[] columns,String selection,String[] selectionArgs,String groupBy,String having,String orderBy) {  
  94.   
  95.         return mDb.query(tableName, columns, selection, selectionArgs, groupBy, having, orderBy);  
  96.     }  
  97.   
  98.     /** 
  99.      * 取得单行记录 
  100.      * 参数:tableName 表名 
  101.      * columns 返回的列 
  102.      * selection 查询条件 
  103.      * selectArgs 如果selection中有“?”号,将用此数组中的值替换 
  104.      *   */  
  105.     public Cursor findInfo(String tableName,String[] columns,String selection,String[] selectionArgs,String groupBy,String having,String orderBy,String limit,boolean distinct) throws SQLException {  
  106.   
  107.         Cursor mCursor = mDb.query(distinct, tableName, columns, selection, selectionArgs, groupBy, having, orderBy, limit);  
  108.           
  109.           
  110.         if (mCursor != null) {  
  111.             mCursor.moveToFirst();  
  112.         }  
  113.         return mCursor;  
  114.   
  115.     }  
  116.   
  117.     /** 
  118.      * 执行sql 
  119.      * 参数:sql 要执行的sql 
  120.       
  121.      *   */  
  122.     public void execSQL(String sql){  
  123.         mDb.execSQL(sql);  
  124.           
  125.     }  
  126.       
  127.     /** 
  128.         * 判断某张表是否存在 
  129.         * @param tabName 表名 
  130.         * @return 
  131.         */  
  132.     public boolean isTableExist(String tableName){  
  133.                boolean result = false;  
  134.                if(tableName == null){  
  135.                        return false;  
  136.                }  
  137.                 
  138.                try {  
  139.                    Cursor cursor = null;  
  140.                        String sql = "select count(1) as c from sqlite_master where type ='table' and name ='"+tableName.trim()+"' ";  
  141.                        cursor = mDb.rawQuery(sql, null);  
  142.                        if(cursor.moveToNext()){  
  143.                                int count = cursor.getInt(0);  
  144.                                if(count>0){  
  145.                                        result = true;  
  146.                                }  
  147.                        }  
  148.                          
  149.                          
  150.                        cursor.close();  
  151.                } catch (Exception e) {  
  152.                        // TODO: handle exception  
  153.                }                  
  154.                return result;  
  155.        }  
  156.            
  157.           
  158.             /** 
  159.             * 判断某张表中是否存在某字段(注,该方法无法判断表是否存在,因此应与isTableExist一起使用) 
  160.             *  
  161.             * @param tabName 表名 
  162.             * @return 
  163.             */  
  164.              public boolean isColumnExist(String tableName,String columnName){  
  165.                    boolean result = false;  
  166.                    if(tableName == null){  
  167.                            return false;  
  168.                    }  
  169.                    
  170.                     
  171.                    try {  
  172.                        Cursor cursor = null;  
  173.                            String sql = "select count(1) as c from sqlite_master where type ='table' and name ='"+tableName.trim()+"' and sql like '%"+ columnName.trim() +"%'" ;  
  174.                            cursor = mDb.rawQuery(sql, null);  
  175.                            if(cursor.moveToNext()){  
  176.                                    int count = cursor.getInt(0);  
  177.                                    if(count>0){  
  178.                                            result = true;  
  179.                                    }  
  180.                            }  
  181.                              
  182.                              
  183.                            cursor.close();  
  184.                    } catch (Exception e) {  
  185.                            // TODO: handle exception  
  186.                    }                  
  187.                    return result;  
  188.            }  
  189.                
  190.                
  191.                
  192.               
  193.   
  194.       
  195. }  


好吧,也顺便写一下各种增删查改的sql。

 

  1. package com.android.mission.test;  
  2.   
  3. import com.android.mission.util.DBHelper;  
  4.   
  5. import android.content.ContentValues;  
  6. import android.database.Cursor;  
  7. import android.test.AndroidTestCase;  
  8. import android.util.Log;  
  9. /** 
  10.  * 单元测试操作sqlLite的各种sql 
  11.  */  
  12. public class testSqlLite extends AndroidTestCase{  
  13.       
  14.     /** 
  15.      * 创建表 
  16.      * @throws Exception 
  17.      */  
  18.     public void createTable() throws Exception{  
  19.         DBHelper dbHelper = new DBHelper(this.getContext());  
  20.         dbHelper.open();  
  21.           
  22.         String deleteSql = "drop table if exists user ";     
  23.         dbHelper.execSQL(deleteSql);  
  24.           
  25.          //id是自动增长的主键,username和 password为字段名, text为字段的类型  
  26.         String sql = "CREATE TABLE user (id integer primary key autoincrement, username text, password text)";    
  27.         dbHelper.execSQL(sql);  
  28.         dbHelper.closeclose();  
  29.     }  
  30.       
  31.     /** 
  32.      * 插入数据 
  33.      * @throws Exception 
  34.      */  
  35.     public void insert() throws Exception{  
  36.         DBHelper dbHelper = new DBHelper(this.getContext());  
  37.         dbHelper.open();  
  38.           
  39.         ContentValues values =  new ContentValues();  //相当于map  
  40.           
  41.         values.put("username""test");  
  42.         values.put("password""123456");  
  43.   
  44.         dbHelper.insert("user", values);  
  45.           
  46.         dbHelper.closeclose();  
  47.     }  
  48.       
  49.     /** 
  50.      * 更新数据 
  51.      * @throws Exception 
  52.      */  
  53.     public void update() throws Exception{  
  54.         DBHelper dbHelper = new DBHelper(this.getContext());  
  55.         dbHelper.open();  
  56.         ContentValues initialValues = new ContentValues();  
  57.         initialValues.put("username""changename");  //更新的字段和值  
  58.         dbHelper.update("user", initialValues, "id = '1'"null);   //第三个参数为 条件语句  
  59.           
  60.         dbHelper.closeclose();  
  61.     }  
  62.       
  63.       
  64.     /** 
  65.      * 删除数据 
  66.      * @throws Exception 
  67.      */  
  68.     public void delete() throws Exception{  
  69.         DBHelper dbHelper = new DBHelper(this.getContext());  
  70.         dbHelper.open();  
  71.           
  72.         String testId = "1";  
  73.         dbHelper.delete("user""id = '"+ testId +"'"null);  
  74.           
  75.         dbHelper.closeclose();  
  76.     }  
  77.       
  78.       
  79.     /** 
  80.      * 增加字段 
  81.      * @throws Exception 
  82.      */  
  83.     public void addColumn() throws Exception{  
  84.         DBHelper dbHelper = new DBHelper(this.getContext());  
  85.         dbHelper.open();  
  86.           
  87.         String updateSql = "alter table user add company text";  
  88.         dbHelper.execSQL(updateSql);  
  89.     }  
  90.       
  91.     /** 
  92.      * 查询列表 
  93.      * @throws Exception 
  94.      */  
  95.     public void selectList()throws Exception{  
  96.         DBHelper dbHelper = new DBHelper(this.getContext());  
  97.         dbHelper.open();  
  98.         Cursor returnCursor = dbHelper.findList("user",new String[] {"id","username""password"}, "username = 'test'"null,nullnull"id desc");  
  99.         while(returnCursor.moveToNext()){  
  100.             String id = returnCursor.getString(returnCursor.getColumnIndexOrThrow("id"));  
  101.             String username = returnCursor.getString(returnCursor.getColumnIndexOrThrow("username"));  
  102.             String password = returnCursor.getString(returnCursor.getColumnIndexOrThrow("password"));  
  103.         }  
  104.     }  
  105.       
  106.     /** 
  107.      * 某条信息 
  108.      * @throws Exception 
  109.      */  
  110.     public void selectInfo()throws Exception{  
  111.         DBHelper dbHelper = new DBHelper(this.getContext());  
  112.         dbHelper.open();  
  113.         Cursor returnCursor = dbHelper.findList("user",new String[] {"id","username""password"}, "id = '1'"null,nullnull"id desc");  
  114.         if (returnCursor.getCount() > 0) {  
  115.             returnCursor.moveToFirst();  
  116.             String id = returnCursor.getString(returnCursor.getColumnIndexOrThrow("id"));  
  117.             String username = returnCursor.getString(returnCursor.getColumnIndexOrThrow("username"));  
  118.             String password = returnCursor.getString(returnCursor.getColumnIndexOrThrow("password"));  
  119.         }  
  120.     }  
  121. }  


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
一个简单的基于AndroidSqlite数据库的操作封装,它有如下的好处:便捷地创建表和增添表字段灵活的数据类型处理通过操作对象来insert或者update表记录支持多种查询方式,支持多表自定义的复杂查询,支持分页查询支持事务快速开始:    1. 设计表:@Table(name="t_user") public class UserModel {     @Table.Column(name="user_id",type=Column.TYPE_INTEGER,isPrimaryKey=true)     public Integer userId;     @Table.Column(name="user_name",type=Column.TYPE_STRING,isNull=false)     public String userName;     @Table.Column(name="born_date",type=Column.TYPE_TIMESTAMP)     public Date bornDate;     @Table.Column(name="pictrue",type=Column.TYPE_BLOB)     public byte[] pictrue;     @Table.Column(name="is_login",type=Column.TYPE_BOOLEAN)     public Boolean isLogin;     @Table.Column(name="weight",type=Column.TYPE_DOUBLE)     public Double weight; }2. 初始化对象:SQLiteDatabase db = context.openOrCreateDatabase("test.db", Context.MODE_PRIVATE, null); DbSqlite dbSqlite = new DbSqlite(db); IBaseDao userDAO = DaoFactory.createGenericDao(dbSqliteUserModel.class);3. 创建表:userDAO.createTable(); 4. Insert 记录:UserModel user = new UserModel(); user.userName = "darcy"; user.isLogin = true; user.weight = 60.5; user.bornDate = new Date(); byte[] picture = {0x1,0x2,0x3,0x4}; user.pictrue = picture; userDAO.insert(user);5. Update 记录:UserModel user = new UserModel(); user.weight = 88.0; userDAO.update(user, "user_name=?", "darcy");6. 查询://单条结果查询 UserModel user = userDAO.queryFirstRecord("user_name=?", "darcy"); //一般查询 List userList = userDAO.query("user_name=? and weight > ?", "darcy" , "60"); //分页查询 PagingList pagingList = userDAO.pagingQuery(nullnull, 1, 3);7. 事务支持:DBTransaction.transact(mDb, new DBTransaction.DBTransactionInterface() {         @Override         public void onTransact() {             // to do                 } };8. 更新表(目前只支持添加字段)@Table(name="t_user" , version=2) //修改表版本 public class UserModel {     //members above...     //new columns     @Table.Column(name="new_column_1",type=Column.TYPE_INTEGER)     public Integer newColumn;     @Table.Column(name="new_column_2",type=Column.TYPE_INTEGER)     public Integer newColumn2; } userDAO.updateTable();缺点和不足:还没支持多对一或者一多的关系没支持联合主键没支持表的外键设计其他...实例:SqliteLookup(Android内查看Sqlite数据库利器): https://github.com/YeDaxia/SqliteLookup 标签:SQLiteUtils

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值