`
android_mylove
  • 浏览: 380264 次
社区版块
存档分类
最新评论

Android学习笔记(5)————SQLite的介绍与相关操作方法

 
阅读更多

/********************************************************************************************
* author:conowen@大钟
* E-mail:conowen@hotmail.com
* http://blog.csdn.net/conowen
* 注:本文为原创,仅作为学习交流使用,转载请标明作者及出处。

********************************************************************************************/


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、创建和打开数据库的方法:

使用openOrCreateDatabase()方法来创建,若数据库不存在,则会创建新数据库,若存在,则打开数据库。和openFileOutput(String filename,mode)的使用差不多,请参看这篇博文,http://blog.csdn.net/conowen/article/details/7296121

openOrCreateDatabase()方法的返回值为一个SQLiteDatabase对象。详细可以参看以下openOrCreateDatabase()方法的官方说明

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

Since: API Level 1

Open a new private SQLiteDatabase associated with this Context's application package. Create the database file if it doesn't exist.

Parameters
name mode factory
The name (unique in the application package) of the database.
Operating mode. Use 0 or MODE_PRIVATE for the default operation,MODE_WORLD_READABLE andMODE_WORLD_WRITEABLE to control permissions.
An optional factory class that is called to instantiate a cursor when query is called.
Returns
  • The contents of a newly created database with the given name.

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

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

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

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

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

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


2.2、关闭SQLite数据库

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


2.3、删除数据库

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



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
sql
the SQL statement to be executed. Multiple statements separated by semicolons are not supported.
Throws
SQLException
if the SQL string is invalid


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



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

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

同样是通过不同的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
sql selectionArgs
the SQL query. The SQL string must not be ; terminated
You 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
table nullColumnHack values
the table to insert the row into
optional; 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.
this 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。



3.3、删除table中的一条数据

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

public intdelete(String table,String whereClause,String[] whereArgs)

Convenience method for deleting rows in the database.

Parameters
tablewhereClause
the table to delete from
the 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
table values whereClause
the table to update in
a map from column names to new column values. null is a valid value that will be translated to NULL.
the 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
table columns selection selectionArgs groupBy having orderBy limit
The table name to compile the query against.
A 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.
A 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.
You 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.
A 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.
A 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.
How 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.
Limits 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子句



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



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


3.6、删除一个table

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


关于SQLite的具体实现例子,可以点击以下的链接,参看另一篇博文

点击打开链接


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics