SQLite用法

SQLiteDataBase是数据库类,SQLiteOpenHelper是用来管理数据库的辅助类

一,SQLiteOpenHelper 类

其中

getReadableDatabase()得到可读的数据库,返回SQLiteDatabase对象,然后通过对象进行数据库操作。

getWritableDatabase()得到可写的数据库,返回SQLiteDatabase对象,然后通过对象进行数据库操作。

onCreate(SQLiteDatabase db)在第一次创建数据库时调用。

onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)在更改数据库时都会调用。

onOpen(SQLiteDatabase db)当数据库打开时调用。

close()关闭数据库。

二,SQLiteDatabase类

这个类提供了对数据库的一些基本操作:

insert()

delete()

update()

query()

。。。。。等等。

代码:

SQLiteOpenHelper 的子类:

  1. import android.content.Context;  
  2. import android.database.sqlite.SQLiteDatabase;  
  3. import android.database.sqlite.SQLiteDatabase.CursorFactory;  
  4. import android.database.sqlite.SQLiteOpenHelper;  
  5.   
  6. /** 
  7.  * 通过getReadableDatabase()和getWritableDatabase()可以获得数据库对象。 
  8.  * 提供onCreate()-创建数据库时,onUpgrade()-升级数据库时,两个回调函数。 
  9.  */  
  10. public class DatabaseHelper extends SQLiteOpenHelper {  
  11.   
  12.     // 按要求必须要有构造函数  
  13.     public DatabaseHelper(Context context, String name, CursorFactory factory,  
  14.             int version) {  
  15.         super(context, name, factory, version);  
  16.     }  
  17.   
  18.     // 当第一次得到SQLiteDatabase对象时,调用该方法  
  19.     @Override  
  20.     public void onCreate(SQLiteDatabase db) {  
  21.         String sql = "create table MSG(id int,body varchar(100))";  
  22.         db.execSQL(sql);  
  23.         System.out.println("创建了一个数据库!");  
  24.     }  
  25.   
  26.     // 当更新数据库时执行该方法  
  27.     @Override  
  28.     public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {  
  29.         System.out.println("更新了数据库!");  
  30.         // 还可以写其他的操作  
  31.     }  
  32. }  

有了这个类后,我们就可以对数据库进行增、删、改、查操作了。
 插入数据:

  1. //生成ContentValues对象,key:列名,value:想插入的值  
  2.                 ContentValues values = new ContentValues();  
  3.                 values.put("id"1);  
  4.                 values.put("body""hello");  
  5.                 DatabaseHelper dbhelper = new DatabaseHelper(SqliteActivity.this"text_msg"null2);  
  6.                 //得到可写的SQLiteDatabase对象  
  7.                 SQLiteDatabase db = dbhelper.getWritableDatabase();  
  8.                 //调用insert方法,将数据插入数据库  
  9.                 //参数1:表名  
  10.                 //参数2:如果你想插入空值,那么你必须指定它的所在的列  
  11.                 db.insert("MSG"null, values);  
  12.                 System.out.println("插入了:1, hello");  

删除数据:

  1. DatabaseHelper dbhelper = new DatabaseHelper(SqliteActivity.this"text_msg"null2);  
  2.                 //得到可写的SQLiteDatabase对象  
  3.                 SQLiteDatabase db = dbhelper.getWritableDatabase();  
  4.                 //调用delete方法,删除数据  
  5.                 db.delete("MSG""id=?"new String[]{"1"});  
  6.                 System.out.println("删除了:id=1");  

修改数据:

  1. ContentValues values = new ContentValues();  
  2.                 values.put("body""my dear!");  
  3.                 DatabaseHelper dbhelper = new DatabaseHelper(SqliteActivity.this"text_msg"null2);  
  4.                 //得到可写的SQLiteDatabase对象  
  5.                 SQLiteDatabase db = dbhelper.getWritableDatabase();  
  6.                 //调用insert方法,将数据插入数据库  
  7.                 //参数3:where 子句 "?"是占位符号,对应后面的"1",这和web开发时的语法是一样的  
  8.                 db.update("MSG", values, "id=?"new String[]{"1"});  
  9.                 System.out.println("更新了:hello-->my dear!");  

查询数据:

  1. DatabaseHelper dbhelper = new DatabaseHelper(SqliteActivity.this"text_msg"null2);  
  2.                 //得到可读的SQLiteDatabase对象  
  3.                 SQLiteDatabase db = dbhelper.getReadableDatabase();  
  4.                 //参数1:表名  
  5.                 //参数2:要想显示的列  
  6.                 //参数3:where子句  
  7.                 //参数4:where子句对应的条件值  
  8.                 //参数5:分组方式  
  9.                 //参数6:having条件  
  10.                 //参数7:排序方式  
  11.                 Cursor cursor = db.query("MSG"new String[]{"id","body"}, "id=?"new String[]{"1"}, nullnullnull);  
  12.                 System.out.println("查到的数据为:");  
  13.                 while(cursor.moveToNext()){  
  14.                         int id = cursor.getInt(cursor.getColumnIndex("id"));  
  15.                         String name = cursor.getString(cursor.getColumnIndex("body"));  
  16.                         System.out.println("-->"+id+"::::::::::"+name);  
  17.                     } 


1、SQLiteDataBase对象的query()接口:
public Cursor  query  (String table, String[] columns, String selection, String[] selectionArgs,
                               String groupBy, String having,String orderBy,String limit)

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

Parameters
table The table name to compile the query against.(要查询的表名.)
columns A list of which columns to return. Passing null will return allcolumns, which is discouraged to prevent reading data from storagethat isn't going to be used.(想要显示的列,若为空则返回所有列,不建议设置为空,如果不是返回所有列)
selection A filter declaring which rows to return, formatted as an SQL WHEREclause (excluding the WHERE itself). Passing null will return allrows for the given table.(where子句,声明要返回的行的要求,如果为空则返回表的所有行。)
selectionArgs You may include ?s in selection, which will be replaced by thevalues from selectionArgs, in order that they appear in theselection. The values will be bound as Strings.( where子句对应的条件值)
groupBy A filter declaring how to group rows, formatted as an SQL GROUP BYclause (excluding the GROUP BY itself). Passing null will cause therows to not be grouped.(分组方式,若为空则不分组.)
having A filter declare which row groups to include in the cursor, if rowgrouping is being used, formatted as an SQL HAVING clause(excluding the HAVING itself). Passing null will cause all rowgroups to be included, and is required when row grouping is notbeing used.(having条件,若为空则返回全部(不建议))
orderBy How to order the rows, formatted as an SQL ORDER BY clause(excluding the ORDER BY itself). Passing null will use the defaultsort order, which may be unordered.(排序方式,为空则为默认排序方式)
limit Limits the number of rows returned by the query, formatted as LIMITclause. Passing null denotes no LIMIT clause.(限制返回的记录的条数,为空则不限制)
Returns
  • Cursor object,which is positioned before the first entry. Notethat Cursorsare not synchronized, see the documentation for more details.
示例:
ContentValues cv = new ContentValues();
String[] args = {String.valueOf("a")};

query("user",new String[] { "username","password" },"username=?"args,null,null,null, null);


2、SQLiteDataBase对象的insert()接口:
publiclong insert (String table, String nullColumnHack, ContentValues values)

Convenience method forinserting a row into the database.

Parameters
table the table to insert the row into(要插入数据的表的名称)
nullColumnHack optional; may be null.SQL doesn't allow inserting a completely empty row without namingat least one column name. If yourprovided valuesisempty, no column names are known and an empty row can't beinserted. If not set to null, the nullColumnHack parameterprovides the name of nullable column name to explicitly insert aNULL into in the case where your values isempty.( 当values参数为空或者里面没有内容的时候,我们insert是会失败的(底层数据库不允许插入一个空行),为了防止这种情况,我们要在这里指定一个列名,到时候如果发现将要插入的行为空行时,就会将你指定的这个列名的值设为null,然后再向数据库中插入。)
values this map contains the initial column values for the row. The keysshould be the column names and the values the columnvalues(一个ContentValues对象,类似一个map.通过键值对的形式存储值。)
Returns
  • the row ID of the newly insertedrow, or -1 if an error occurred
示例:
ContentValues cv = new ContentValues();
cv.put( "username" "a" );
cv.put( "password" "b" );
insert("user" null ,cv);
 
 
3、SQLiteDataBase对象的update()接口:
publicint update (String table, ContentValues values, String whereClause, String[] whereArgs)

Convenience method for updatingrows in the database.

Parameters
table the table to update in(要更新的表名)
values a map from column names to new column values. null is a valid valuethat will be translated to NULL.(一个ContentValues对象,类似一个map.通过键值对的形式存储值。)
whereClause


whereArgs
the optional WHERE clause to apply when updating. Passing null willupdate all rows.(可选的where语句)

the group of args to dealwith(whereClause语句中表达式的?占位参数列表
)
Returns
  • the number of rows affected
ContentValues cv = new ContentValues();
cv.put("username" "c" );
cv.put("password" "d" );
String[] args = {String.valueOf( "a" )};
update("user",cv, "username=?",args)
 
 
4、SQLiteDataBase对象的delete()接口:
publicint delete (String table, String whereClause, String[] whereArgs)

Convenience method for deletingrows in the database.

Parameters
table the table to delete from
whereClause

whereArgs
the optional WHERE clause to apply when deleting. Passing null willdelete all rows.(可选的where语句)
the optional WHERE clauseto apply when updating. Passing null will update allrows.(whereClause语句中表达式的?占位参数列表)
Returns
  • the number of rows affected if awhereClause is passed in, 0 otherwise. To remove all rows and get acount pass "1" as the whereClause.
示例:
ContentValues cv = new ContentValues();
String[] args = {String.valueOf( "c" )};
delete("user" "username=?" ,args);



SQLiteOpenHelper:是一个辅助类,这个类主要用于生产一个数据库,并对数据库的版本进行管理。此类为一抽象类,使用是需要继承此类并实现该类的方法
onCreate(SQLiteDatabase):在数据库第一次生产的时候会调用这个方法,一般我们在这个方法里边生产数据库表。
onUpgrade(SQLiteDatabase,int,int):当数据库需要升级的时候,Android系统会主动的调用这个方法。一般我们在这个方法里边删除数据库表,并建立新的数据库表,当然是否还需要做其他的操作,完全取决于应用程序的需求。
onOpen(SQLiteDatabase):这是当打开数据库时的回调函数,一般也不会用到。

   调用程序方法返回SQLiteDatabase对象。
当在程序当中调用这个类的方法getWritableDatabase()或者getReadableDatabase()方法的时候,如果当时没有数据,那么Android系统就会自动生产一个数据库。数据库使用完后记得调用close()方法关闭数据库。


创建数据库类:
Java代码   收藏代码
  1. public class DatabaseHelper extends SQLiteOpenHelper {  
  2.   
  3.     private static final String TABLE_NAME = "itss"//数据库名称  
  4.     private static final int version = 1//数据库版本  
  5.     private String TITLE = "title";  
  6.     private String BODY = "body";  
  7.       
  8.     public DatabaseHelper(Context context) {  
  9.         super(context, TABLE_NAME, null, version);  
  10.         // TODO Auto-generated constructor stub  
  11.     }  
  12.   
  13.     @Override  
  14.     public void onCreate(SQLiteDatabase db) {  
  15.         String sql = "create table "+TABLE_NAME+" ("+TITLE+" text not null , "+BODY+" text not null );";  
  16.               
  17.         Log.i("haiyang:createdb=", sql);  
  18.               
  19.         db.execSQL(sql);  
  20.     }  
  21.   
  22.     @Override  
  23.     public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {  
  24.         // TODO Auto-generated method stub  
  25.   
  26.     }  
  27.   
  28. }  


调用方法:
Java代码  
  1. DatabaseHelper database = new DatabaseHelper(this  
  2.                     .getApplicationContext());  
  3. Log.i("haiyang:createdb=""执行失败");  
  4. SQLiteDatabase db = null;  
  5. try  
  6. {  
  7.     db = database.getWritableDatabase();  
  8. }  
  9. catch (SQLiteException ex)  
  10. {  
  11.     db = database.getReadableDatabase();  



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值