Android中SQLite数据库存储方式 .(转)

http://www.apkbus.com/android-17716-1-1.html 

Android中的数据库存储是直接使用了SQLite。在Android应用中创建数据库后数据库文件是存储在/data/ data/应用包名/databases/下。

 

在Android中使用到SQLite会涉及到以下三个类或接口:
1.SQLiteOpenHelper

*SQLiteOpenHelper 构造方法,一般传递一个要创建的数据库名称name参数
*onCreate 创建数据库时调用
*onUpgrade 版本更新时调用
*getReadableDatabase 创建或打开一个只读数据库
*getWritableDatabase 创建或打开一个读写数据库

2.SQLiteDatabase
*openOrCreateDatabase 打开或者创建数据库
*insert 添加一条记录
*delete 删除一条记录
*query 查询记录
*update 更新记录
*execSQL 执行一条SQL语句
*close 关闭数据库

3.Cursor
*getCount 总记录条数
*isFirst 判断是否第一条记录
*isLast 判断是否最后一条记录
*moveToFirst 移动到第一条记录
*moveToLast 移动到最后一条记录
*move 移动到指定记录
*moveToNext 移动到下一条记录
*moveToPrevious 移动到上一条记录
*getColumnIndexOrThrow根据列名称获得列索引
*getInt 获得指定列索引的int类型值
*getString 获得指定列索引的String类型值
注:某些方法是有重载的,可以结合docs熟悉下。

 

下面贴上数据库操作的代码,完整代码下载地址:android_sqlite.rar

1.创建数据库只要自定义一个类继承SQLiteOpenHelper即可。在SQLiteOpenHelper的子类中至少需要实现三个方法:
*构造方法,调用父类SQLiteOpenHelper的构造函数。需要四个参数:上下文环境(例如一个Activity);数据库名称;一个可选的游标工
厂(通常是null);一个正在使用的数据库版本。
*onCreate方法,需要一个SQLiteDatabase对象作为参数,根据需要对这个对象填充表和初始化数据。
*onUpgrade方法,需要三个参数:一个SQLiteDatabase对象,一个旧的版本号和一个新的版本号。

  1. /** 
  2.  * 数据库操作助手类 
  3.  *  
  4.  * @author zuolongsnail 
  5.  */  
  6. public class AndroidSQLiteOpenHelper extends SQLiteOpenHelper {  
  7.   
  8.     // 数据库名称   
  9.     public static final String DBNAME = "android.db";  
  10.     // 数据库版本   
  11.     public static final int VERSION = 2;  
  12.     // 建表语句,大小写不敏感   
  13.     private static final String CREATETABLE = "create table "  
  14.             + Person.TABLENAME  
  15.             + "(id string, name string, gender int, age int)";  
  16.   
  17.     public AndroidSQLiteOpenHelper(Context context) {  
  18.         super(context, DBNAME, null, VERSION);  
  19.     }  
  20.   
  21.     // 创建表   
  22.     @Override  
  23.     public void onCreate(SQLiteDatabase db) {  
  24.         db.execSQL(CREATETABLE);  
  25.     }  
  26.   
  27.     // 更新表   
  28.     @Override  
  29.     public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {  
  30.         this.deleteDB(db);  
  31.         this.onCreate(db);  
  32.     }  
  33.   
  34.     // 删除表   
  35.     private void deleteDB(SQLiteDatabase db) {  
  36.         db.execSQL("drop table if exists " + Person.TABLENAME);  
  37.     }  
  38. }  

2.对数据库表进行操作,包括添加、删除、修改和查询。(下面的代码使用的是第一种方法)
有两种方法可以对数据库表进行操作:使用execSQL方法执行SQL语句;使用insert、delete、update和query方法,把SQL语句的一部分
作为参数。
注:查询数据库时执行SQL语句是使用SQLiteDatabase的rawQuery方法而不是execSQL。 

  1. /** 
  2.  * 数据库管理类 
  3.  *  
  4.  * @author zuolongsnail 
  5.  *  
  6.  */  
  7. public class DatabaseManager {  
  8.   
  9.     private AndroidSQLiteOpenHelper dbHelper;  
  10.   
  11.     public DatabaseManager(Context context) {  
  12.         dbHelper = new AndroidSQLiteOpenHelper(context);  
  13.     }  
  14.   
  15.     // 插入记录   
  16.     public int insert(Person person) {  
  17.         Log.e("SQLite""----insert----");  
  18.         SQLiteDatabase db = dbHelper.getWritableDatabase();  
  19.         db.beginTransaction();  
  20.         try {  
  21.             db.execSQL("insert into " + Person.TABLENAME  
  22.                     + " values(?, ?, ?, ?)"new Object[] { person.id,  
  23.                     person.name, person.gender, person.age });  
  24.             db.setTransactionSuccessful();  
  25.         } catch (Exception e) {  
  26.             return 0;  
  27.         } finally {  
  28.             db.endTransaction();  
  29.         }  
  30.         db.close();  
  31.         return 1;  
  32.     }  
  33.   
  34.     // 删除记录   
  35.     public int delete(Person person) {  
  36.         Log.e("SQLite""----delete----");  
  37.         SQLiteDatabase db = dbHelper.getWritableDatabase();  
  38.         db.beginTransaction();  
  39.         try {  
  40.             db.execSQL("delete from " + Person.TABLENAME + " where id = ?",  
  41.                     new Object[] { person.id });  
  42.             db.setTransactionSuccessful();  
  43.         } catch (Exception e) {  
  44.             return 0;  
  45.         } finally {  
  46.             db.endTransaction();  
  47.         }  
  48.         db.close();  
  49.         return 1;  
  50.     }  
  51.   
  52.     // 更新记录   
  53.     public int update(Person person) {  
  54.         Log.e("SQLite""----update----");  
  55.         SQLiteDatabase db = dbHelper.getWritableDatabase();  
  56.         db.beginTransaction();  
  57.         try {  
  58.             db.execSQL("update " + Person.TABLENAME  
  59.                     + " set name=?, gender=?, age=? where id=?"new Object[] {  
  60.                     person.name, person.gender, person.age, person.id });  
  61.             db.setTransactionSuccessful();  
  62.         } catch (Exception e) {  
  63.             return 0;  
  64.         } finally {  
  65.             db.endTransaction();  
  66.         }  
  67.         db.close();  
  68.         return 1;  
  69.     }  
  70.   
  71.     // 查询记录   
  72.     public ArrayList<Person> query(String id) {  
  73.         Log.e("SQLite""----query----");  
  74.         SQLiteDatabase db = dbHelper.getReadableDatabase();  
  75.         Cursor cursor;  
  76.         Person person;  
  77.         ArrayList<Person> list = new ArrayList<Person>();  
  78.         // 若fileId为null或""则查询所有记录   
  79.         if (id == null || id.equals("")) {  
  80.             cursor = db.rawQuery("select * from " + Person.TABLENAME, null);  
  81.         } else {  
  82.             cursor = db.rawQuery("select * from " + Person.TABLENAME  
  83.                     + " where id=?"new String[] { id });  
  84.         }  
  85.         while (cursor.moveToNext()) {  
  86.             person = new Person();  
  87.             person.id = cursor.getString(cursor.getColumnIndex("id"));  
  88.             person.name = cursor.getString(cursor.getColumnIndex("name"));  
  89.             person.gender = cursor.getString(cursor.getColumnIndex("gender"));  
  90.             person.age = cursor.getInt(cursor.getColumnIndex("age"));  
  91.             Log.e("SQLite", person.toString());  
  92.             list.add(person);  
  93.         }  
  94.         cursor.close();  
  95.         db.close();  
  96.         if (list.size() == 0) {  
  97.             Log.e("SQLite""****表中无数据****");  
  98.         }  
  99.         return list;  
  100.     }  
  101. }  

3、SQLite数据库中(Table )“表”的操作方法


        首先要明确一点的是,一个数据库可以有很多表,一个表中包含很多条数据,也就是说,在数据库里面保存数据其实是保存在Table (表)里面的。对已经存在和已经创建的数据库操作一般包括:创建表,往表添加数据,从表中删除数据,修改表中的数据,查询表中的数据,删除已存在的表。


3.1创建一个表

通过调用数据库的execSQL (String sql)方法可以创建一个table(表),关于execSQL(String sql)方法的详细可以参看以下的官方说明。

public void execSQL(String sql)
Since: API Level 1

Execute a single SQL statement that is NOT a SELECT or any other SQL statement that returns data.

It has no means to return any data (such as the number of affected rows). Instead, you're encouraged to useinsert(String, String, ContentValues),update(String, ContentValues, String, String[]), et al, when possible.

When using enableWriteAheadLogging(), journal_mode is automatically managed by this class. So, do not set journal_mode using "PRAGMA journal_mode'" statement if your app is using enableWriteAheadLogging()

Parameters
sqlthe SQL statement to be executed. Multiple statements separated by semicolons are not supported.
Throws
SQLExceptionif the SQL string is invalid


 


事实上,execSQL (String sql)方法的参数“sql“是SQL语句,为字符串类型。如

  1. SQLiteDatabase db;  
  2.  String sql = "CREATE  TABLE pic (_id INTEGER PRIMARY KEY , filename VARCHAR, data TEXT)";  
  3. db.execSQL(sql);  



关于SQL语句可参看相关SQL的编程资料。

另外通过execSQL()方法,还可以实现向表中“插入”数据,“删除”数据。

同样是通过不同的SQL语句实现的。

  1. db.execSQL(sql);//sql为标准的SQL语句  



 

另外:读取表中数据也可以用rawQuery();方法来读取。

public Cursor rawQuery (String sql,String[] selectionArgs)
Since: API Level 1

Runs the provided SQL and returns a Cursor over the result set.

Parameters
sqlthe SQL query. The SQL string must not be ; terminated
selectionArgsYou may include ?s in where clause in the query, which will be replaced by the values from selectionArgs. The values will be bound as Strings.
Returns
  • A Cursor object, which is positioned before the first entry. Note thatCursors are not synchronized, see the documentation for more details.

        虽然db.execSQL(sql);方法也可以实现insert和delete操作,另外db.rawQuery(sql, selectionArgs);也可以查询表中的某一条数据,但是由于涉及到标准SQL语句,所以一般来说,除了新建table是用execSQL(sql)方法和3.6点的删除一个table,其他的如insert,delete,query操作还是建议使用以下方法。


3.2、向表中插入一条数据

          往数据库的table插入数据,可以直接调用db.insert()方法插入,但是insert()方法中的第三个参数是一个ContentValues的,其实也就是一个map,包含了一些键值对(key-value)。通过contentValues的put方法,可以把键值对放进contentValues里面,然后再通过db.insert()方法插到数据库的table中。

public long insert(String table,String nullColumnHack, ContentValues values)
Since: API Level 1

Convenience method for inserting a row into the database.

Parameters
tablethe table to insert the row into
nullColumnHackoptional; may be null. SQL doesn't allow inserting a completely empty row without naming at least one column name. If your providedvalues is empty, no column names are known and an empty row can't be inserted. If not set to null, thenullColumnHack parameter provides the name of nullable column name to explicitly insert a NULL into in the case where yourvalues is empty.
valuesthis map contains the initial column values for the row. The keys should be the column names and the values the column values
Returns
  • the row ID of the newly inserted row, or -1 if an error occurred

insert的第一个参数是table的名字,第二个参数一般为null,第三个参数是contentValues。若成功insert,就返回新插入row的id,不成功返回-1。

  1. ContentValues cv =new contentValues();  
  2. cv.put(num,1);  
  3. cv.put(data," 测试我的数据库");  
  4. db.insert(table,null,cv);  


3.3、删除table中的一条数据

直接调用数据库的db.delete()方法。

public intdelete(String table,String whereClause,String[] whereArgs)
Since: API Level 1

Convenience method for deleting rows in the database.

Parameters
tablethe table to delete from
whereClausethe optional WHERE clause to apply when deleting. Passing null will delete all rows.
Returns
  • the number of rows affected if a whereClause is passed in, 0 otherwise. To remove all rows and get a count pass "1" as the whereClause.
第一个参数————table名
第二个参数————删除的条件,为字符串。如果为null,则所有行都将删除。
第三个参数————字符串数组,和whereClause配合使用。
                                 用法一、如果whereClause的条件已经直接给出,如“name= “ + num,num是传入的参数。则whereArgs可设为null。
                                 用法二、当在whereClause中包含”?”时,则whereArgs这个数组中的值将依次替换whereClause中出现的”?”


3.4、修改表中数据

调用db.update()方法

public int update(String table,ContentValues values,String whereClause,String[] whereArgs)
Since: API Level 1

Convenience method for updating rows in the database.

Parameters
tablethe table to update in
valuesa map from column names to new column values. null is a valid value that will be translated to NULL.
whereClausethe optional WHERE clause to apply when updating. Passing null will update all rows.
Returns
  • the number of rows affected

update()的是个参数请参看上面几个方法的说明。


3.5、查询表中的数据

调用db.query()方法。

public Cursor query (String table,String[] columns,String selection, String[] selectionArgs,String groupBy,String having,String orderBy,String limit)
Since: API Level 1

Query the given table, returning a Cursor over the result set.

Parameters
tableThe table name to compile the query against.
columnsA list of which columns to return. Passing null will return all columns, which is discouraged to prevent reading data from storage that isn't going to be used.
selectionA filter declaring which rows to return, formatted as an SQL WHERE clause (excluding the WHERE itself). Passing null will return all rows for the given table.
selectionArgsYou may include ?s in selection, which will be replaced by the values from selectionArgs, in order that they appear in the selection. The values will be bound as Strings.
groupByA filter declaring how to group rows, formatted as an SQL GROUP BY clause (excluding the GROUP BY itself). Passing null will cause the rows to not be grouped.
havingA filter declare which row groups to include in the cursor, if row grouping is being used, formatted as an SQL HAVING clause (excluding the HAVING itself). Passing null will cause all row groups to be included, and is required when row grouping is not being used.
orderByHow to order the rows, formatted as an SQL ORDER BY clause (excluding the ORDER BY itself). Passing null will use the default sort order, which may be unordered.
limitLimits the number of rows returned by the query, formatted as LIMIT clause. Passing null denotes no LIMIT clause.
Returns
  • A Cursor object, which is positioned before the first entry. Note thatCursors are not synchronized, see the documentation for more details.

参数说明:

table————要查询数据的表名

 

columns————要返回列的列名数组

 

selection————可选的where子句 ,如果为null,将会返回所有的行

                                                                                                                      

selectionArgs————当在selection中包含”?”时,如果selectionArgs的值不为null,则这个数组中的值将依次替换selection中出现的”?”

 

groupBy————可选的group by子句,如果其值为null,将不会对行进行分组

 

having————可选的having子句,如果其值为null,将会包含所有的分组

 

orderBy————可选的order by子句,如果其值为null,将会使用默认的排序规则

 

limit————可选的limit子句,如果其值为null,将不会包含limit子句


  1. Cursor cr=db.query("pic"nullnullnullnull,nullnull);//查询数据库的所有数据  


 

返回值类型为Cursor(游标),Cursor的操作示意图



然后通过调用Cursor的相关方法来操作查询到的数据,关于Cursor的使用方法可以参看官方的说明文档,下面列出一些常用的方法:


3.6、删除一个table

通过db.execSQL(sql)方法实现,参数sql是SQL标准语句

  1. db.execSQl("DROP TABLE mytable");  

 

 

使用  insete

   // 通过helper的getWritableDatabase()得到SQLiteOpenHelper所创建的数据库  

  •         Button insert = (Button) findViewById(R.id.insert);  
  •         Button delete = (Button) findViewById(R.id.delete);  
  •         Button update = (Button) findViewById(R.id.update);  
  •         Button query = (Button) findViewById(R.id.query);  
  •         final ContentValues cv = new ContentValues();  
  •         // ContentValues是“添加”和“更新”两个操作的数据载体  
  •         updatelistview();// 更新listview  
  •         // 添加insert   
  •         insert.setOnClickListener(new OnClickListener() {  
  •   
  •             @Override  
  •             public void onClick(View v) {  
  •                 // TODO Auto-generated method stub  
  •                 EditText et_name = (EditText) findViewById(R.id.name);  
  •                 EditText et_phone = (EditText) findViewById(R.id.phone);  
  •                 cv.put("name", et_name.getText().toString());  
  •                 cv.put("phone", et_phone.getText().toString());  
  •                 // name和phone为列名   
  •                 long res = sqldb.insert("addressbook"null, cv);// 插入数据  
  •                 if (res == -1) {  
  •                     Toast.makeText(SqliteActivity.this"添加失败",  
  •                             Toast.LENGTH_SHORT).show();  
  •                 } else {  
  •                     Toast.makeText(SqliteActivity.this"添加成功",  
  •                             Toast.LENGTH_SHORT).show();  
  •                 }  
  •                 updatelistview();// 更新listview  
  •             }  
  •         });  
  •         // 删除   
  •         delete.setOnClickListener(new OnClickListener() {  
  •   
  •             @Override  
  •             public void onClick(View v) {  
  •                 // TODO Auto-generated method stub  
  •                 int res = sqldb.delete("addressbook""name='大钟'"null);  
  •                 // 删除列名name,行名为“大钟”的,这一行的所有数据,null表示这一行的所有数据  
  •                 // 若第二个参数为null,则删除表中所有列对应的所有行的数据,也就是把table清空了。  
  •                 // name='大钟',大钟要单引号的  
  •                 // 返回值为删除的行数   
  •                 if (res == 0) {  
  •                     Toast.makeText(SqliteActivity.this"删除失败",  
  •                             Toast.LENGTH_SHORT).show();  
  •                 } else {  
  •                     Toast.makeText(SqliteActivity.this"成删除了" + res + "行的数据",  
  •                             Toast.LENGTH_SHORT).show();  
  •                 }  
  •                 updatelistview();// 更新listview  
  •   
  •             }  
  •         });  
  •         // 更改   
  •         update.setOnClickListener(new OnClickListener() {  
  •   
  •             @Override  
  •             public void onClick(View v) {  
  •                 // TODO Auto-generated method stub  
  •                 cv.put("name""大钟");  
  •                 cv.put("phone""1361234567");  
  •                 int res = sqldb.update("addressbook", cv, "name='张三'"null);  
  •                 // 把name=张三所在行的数据,全部更新为ContentValues所对应的数据  
  •                 // 返回时为成功更新的行数   
  •                 Toast.makeText(SqliteActivity.this"成功更新了" + res + "行的数据",  
  •                         Toast.LENGTH_SHORT).show();  
  •   
  •                 updatelistview();// 更新listview  
  •             }  
  •         });  
  •         // 查询   
  •         query.setOnClickListener(new OnClickListener() {  
  •   
  •             @Override  
  •             public void onClick(View v) {  
  •                 // TODO Auto-generated method stub  
  •                 Cursor cr = sqldb.query("addressbook"nullnullnullnull,  
  •                         nullnull);  
  •                 // 返回名为addressbook的表的所有数据  
  •                 Toast.makeText(SqliteActivity.this,  
  •                         "一共有" + cr.getCount() + "条记录", Toast.LENGTH_SHORT)  
  •                         .show();  
  •   
  •                 updatelistview();// 更新listview  
  •             }  
  •         });  
  •   
  •     }  

     

    3.在shell中进入sqlite并使用sql语句操作数据库,如下图所示。

    *启动命令行,执行adb shell命令,前提是启动了一个模拟器。

     

    *进入/data/ data/应用包名/databases文件夹下,我们这里是/data/data/code.sqlite/databases(确保此应用已经建立数据库,不然包名下是没有databases目录的)。

    *查看databases目录下的数据库文件,这里可以看到数据库文件是android.db。

    *使用sqlite3命令进入sqlite来使用sql语句操作数据库,我们执行"sqlite3 android.db"命令。

    *使用".tables"命令查询数据库下有哪些表。可见我们这里有一张person表。

    *使用sql语句可以操作这张表,比如我们使用"select * from person;"可以查询到表中记录。

    *使用".quit"命令可以退出sqlite。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值