Android學習筆記(5)————SQLite的介紹與相關操作方法

來源:互聯網
上載者:User

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

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
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語句,為字串類型。如

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

關於SQL語句可參看相關SQL的編程資料。

另外通過execSQL()方法,還可以實現向表中“插入”資料,“刪除”資料。

同樣是通過不同的SQL語句實現的。

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
sql the SQL query. The SQL string must not be ; terminated
selectionArgs 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 the table to insert the row into
nullColumnHack 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.
values 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。

ContentValues cv =new contentValues();cv.put(num,1);cv.put(data," 測試我的資料庫");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
table the table to delete from
whereClause 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 the table to update in
values a map from column names to new column values. null is a valid value that will be translated to NULL.
whereClause 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 The table name to compile the query against.
columns 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.
selection 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.
selectionArgs 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.
groupBy 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.
having 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.
orderBy 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.
limit 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 cr=db.query("pic", null, null, null, null,null, null);//查詢資料庫的所有資料

傳回值類型為Cursor(遊標),Cursor的操作

然後通過調用Cursor的相關方法來操作查詢到的資料,關於Cursor的使用方法可以參看官方的說明文檔,下面列出一些常用的方法:

3.6、刪除一個table

通過db.execSQL(sql)方法實現,參數sql是SQL標準語句

db.execSQl("DROP TABLE mytable");

關於SQLite的具體實現例子,可以點擊以下的連結,參看另一篇博文

點擊開啟連結

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.