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


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
nameThe name (unique in the application package) of the database.
modeOperating mode. Use 0 or MODE_PRIVATE for the default operation,MODE_WORLD_READABLE andMODE_WORLD_WRITEABLE to control permissions.
factoryAn 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()方法即可,如:

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



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语句,为字符串类型。如

[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);  


关于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.

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,要插入的值value
成功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);  


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设置为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
  • 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);//查询数据库的所有数据  

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



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


3.6、删除一个table

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

[java]  view plain copy
  1. db.execSQl("DROP TABLE mytable");  

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

点击打开链接


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值