android下SQLite学习笔记

参考博客http://blog.csdn.net/conowen/article/details/7276417

1、SQLite简单介绍

SQ为Structured Query (结构化查询)的缩写,Lite表示轻量级。SQLite是一款开源的关系型数据库。几乎可以支持所有现代编程语言和各种操作系统,SQLite的最新版本为SQLite 3。


SQLite的特性: 
1. ACID事务 
2. 零配置 – 无需安装和管理配置 
3. 储存在单一磁盘文件中的一个完整的数据库 
4. 数据库文件可以在不同字节顺序的机器间自由的共享 
5. 支持数据库大小至2TB 
6. 足够小, 大致3万行C代码, 250K , 运行时占用内存大概几百K。
7. 比一些流行的数据库在大部分普通数据库操作要快 
8. 简单, 轻松的API 
9. 包含TCL绑定, 同时通过Wrapper支持其他语言的绑定 
10. 良好注释的源代码, 并且有着90%以上的测试覆盖率 
11. 独立: 没有额外依赖 
12. Source完全的Open, 你可以用于任何用途, 包括出售它 
13. 支持多种开发语言,C, PHP, Perl, Java, ASP.NET,Python 



2、SQLite数据库相关操作方法

对SQLite数据库的操作一般包括:创建一个数据库,打开数据库,关闭数据库,删除数据库。


2.1、创建和打开数据库的方法:

public SQLiteDatabase openOrCreateDatabase (String name, int mode, SQLiteDatabase.CursorFactory factory)

使用openOrCreateDatabase()方法来创建,若数据库不存在,则会创建新数据库,若存在,则打开数据库。

第一个参数————为数据库的名字,string类型。

第二个参数————为常量,如下所示

常量                                                                             含义
MODE_PRIVATE                          默认模式,值为0,文件只可以被调用该方法的应用程序访问

MODE_WORLD_READABLE            所有的应用程序都具有对该文件读的权限。

MODE_WORLD_WRITEABLE            所有的应用程序都具有对该文件写的权限。

第三个参数————当query方法被调用时,用来实例化cursor,通常为null

返回值为一个SQLiteDatabase对象


2.2、关闭SQLite数据库  db.close()

对数据库操作完毕之后,就要关闭数据库,否则会抛出SQLiteException异常。关闭数据库只需调用成SQLiteDatabase对象的.close()方法即可。


2.3、删除数据库 

直接调用deleteDatebase()方法即可,如:

[java]  view plain copy
  1. this.deleteDatabase("mysqlite.db")  



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


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


3.1创建一个表   public void execSQL(String sql)


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

params

sql 一般的sql语句

throws

SQLException 如果SQL语句有错误

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

[java]  view plain copy
  1. SQLiteDatabase db;  
  2.  String sql = "CREATE  TABLE pic (_id INTEGER PRIMARY KEY , filename VARCHAR, data TEXT)";  
  3. db.execSQL(sql);  
其中,android默认_id INTEGER PRIMARY KEY,必须加上,否则报错,可以写为CREATE  TABLE pic (_id INTEGER PRIMARY KEY AUTOINCREMENT , filename VARCHAR, data TEXT)这样可以自动递增表号,读取数据时作为行号.不读即可.

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

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

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

[java]  view plain copy
  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
  • 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.

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

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

  1. ContentValues cv = new ContentValues(); 
  2. cv.put("name", et_name.getText().toString());  
  3. cv.put("phone", et_phone.getText().toString());  
  4.                 // name和phone为列名  
  5. long res = sqldb.insert("addressbook"null, cv);// 插入数据  
  6.  if (res == -1) {  
  7.        Toast.makeText(SqliteActivity.this"添加失败",  
  8.        Toast.LENGTH_SHORT).show();  
  9.   } else {  
  10.         Toast.makeText(SqliteActivity.this"添加成功",  
  11.         Toast.LENGTH_SHORT).show();  
  12.   }  


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中出现的”?”

  1. int res = sqldb.delete("addressbook""name='大钟'"null);  
  2.                 // 删除列名name,行名为“大钟”的,这一行的所有数据,null表示这一行的所有数据  
  3.                 // 若第二个参数为null,则删除表中所有列对应的所有行的数据,也就是把table清空了。  
  4.                 // name='大钟',大钟要单引号的  
  5.                 // 返回值为删除的行数  
  6.                 if (res == 0) {  
  7.                     Toast.makeText(SqliteActivity.this"删除失败",  
  8.                             Toast.LENGTH_SHORT).show();  
  9.                 } else {  
  10.                     Toast.makeText(SqliteActivity.this"成删除了" + res + "行的数据",  
  11.                             Toast.LENGTH_SHORT).show();  
  12.                 }  

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()的是个参数请参看上面几个方法的说明。

  1. cv.put("name""大钟");  
  2.                 cv.put("phone""1361234567");  
  3.                 int res = sqldb.update("addressbook", cv, "name='张三'"null);  
  4.                 // 把name=张三所在行的数据,全部更新为ContentValues所对应的数据  
  5.                 // 返回时为成功更新的行数  
  6.                 Toast.makeText(SqliteActivity.this"成功更新了" + res + "行的数据",  
  7.                         Toast.LENGTH_SHORT).show();  


3.5、查询表中的数据

调用db.query()方法。

public Cursor query (String table,String[] columns,String selection, String[] selectionArgs,String groupBy,Stringhaving,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
  • 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子句


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

db.query(TABLE_NAME,new String[]{"_id","task_no","cons_no"},"task_no=? or task_no=?",

new String[]{"1234","2345"},null,null,null);

查询表中,查找task_no=1234 task_no=2345对应列名为"_id","task_no","cons_no"的数据

"1234","2345"代替"task_no=? or task_no=?"所在的问号

相当 select _id,task_no,cons_no from TABLE_NAME where task_no="1234" or task_no="2345";


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



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


3.6、删除一个table

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

db.execSQl("DROP TABLE mytable");


  

利用SQLiteOpenHelper来管理SQLite数据库

SQLiteOpenHelper可以创建数据库,和管理数据库的版本。

在继承SQLiteOpenHelper的类(extends SQLiteOpenHelper)里面,通过复写onCreate(SQLiteDatabase),onUpgrade(SQLiteDatabase, int, int) 和onOpen(SQLiteDatabase)(可选)来操作数据库。


4.1、SQLiteOpenHelper()的具体用法

创建一个新的class如下所示,onCreate(SQLiteDatabase db)和onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)方法会被自动添加。

  1.   
  2. package com.conowen.sqlite;  
  3.   
  4. import android.content.Context;  
  5. import android.database.sqlite.SQLiteDatabase;  
  6. import android.database.sqlite.SQLiteDatabase.CursorFactory;  
  7. import android.database.sqlite.SQLiteOpenHelper;  
  8.   
  9. public class DBHelper extends SQLiteOpenHelper{  
  10.   
  11.     public DbHelper(Context context, String name, CursorFactory 
  12. factory,int version) {  
  13.         super(context, name, factory, version);  
  14.         // TODO Auto-generated constructor stub  
  15.     }  
  16.   
  17.     @Override  
  18.     public void onCreate(SQLiteDatabase db) {  
  19.         // TODO Auto-generated method stub  
  20.        String sql = "CREATE TABLE table_name(_id INTEGER PRIMARY KEY,"+
  21.        "filename VARCHAR, data TEXT)";
  22.        db.execSQL(sql);//创建成功后会在机子的data/data/<package name>/databases文件中
  23.           
  24.     }  
  25.   
  26.     @Override  
  27.     public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {  
  28.         // TODO Auto-generated method stub  
  29.           
  30.     }  
  31.   
  32. }  
方法介绍:1 
  1.  public DbHelper(Context context, String name, CursorFactory 
  2. factory,int version) {  
  3.         super(context, name, factory, version);  
  4.         // TODO Auto-generated constructor stub  
  5.     }  

以上是SQLiteOpenHelper 的构造函数,当数据库不存在时,就会创建数据库,然后打开数据库(过程已经被封装起来了),再调用onCreate (SQLiteDatabase db)方法来执行创建表之类的操作。当数据库存在时,SQLiteOpenHelper 就不会调用onCreate (SQLiteDatabase db)方法了,它会检测版本号,若传入的版本号高于当前的,就会执行onUpgrade()方法来更新数据库和版本号。


2  oncreate 方法

public abstract void onCreate (SQLiteDatabase db)

Since: API Level 1

Called when the database is created for the first time. This is where the creation of tables and the initial population of the tables should happen.


3 onUpgrade方法

public abstract void onUpgrade (SQLiteDatabase db, int oldVersion, int newVersion) 

        更新数据库,包括删除表,添加表等各种操作。若版本是第一版,也就是刚刚建立数据库,onUpgrade()方法里面就不用写东西,因为第一版数据库何来更新之说,以后发布的版本,数据库更新的话,可以在onUpgrade()方法添加各种更新的操作。

4、注意事项

创建完SQLiteOpenHelper 类之后,在主activity里面就可以通过SQLiteOpenHelper.getWritableDatabase()或者getReadableDatabase()方法来获取在SQLiteOpenHelper 类里面创建的数据库实例。(也就是说只有调用这两种方法才真正地实例化数据库)

getWritableDatabase() 方法————以读写方式打开数据库,如果数据库所在磁盘空间满了,而使用的又是getWritableDatabase() 方法就会出错。

                                                                         因为此时数据库就只能读而不能写,

getReadableDatabase()方法————则是先以读写方式打开数据库,如果数据库的磁盘空间满了,就会打开失败,但是当打开失败后会继续尝试以只读

                                                                          方式打开数据库。而不会报错





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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值