Android SQLite數(shù)據(jù)庫(kù)基本操作方法
程序的最主要的功能在于對(duì)數(shù)據(jù)進(jìn)行操作,通過(guò)對(duì)數(shù)據(jù)進(jìn)行操作來(lái)實(shí)現(xiàn)某個(gè)功能。而數(shù)據(jù)庫(kù)就是很重要的一個(gè)方面的,Android中內(nèi)置了小巧輕便,功能卻很強(qiáng)的一個(gè)數(shù)據(jù)庫(kù)–SQLite數(shù)據(jù)庫(kù)。那么就來(lái)看一下在Android程序中怎么去操作SQLite數(shù)據(jù)庫(kù)來(lái)實(shí)現(xiàn)一些需求的吧,仍然以一個(gè)小例子開始:
在創(chuàng)建Android項(xiàng)目之前,我們應(yīng)該想一下我們要定義的數(shù)據(jù)庫(kù)的相關(guān)信息和里面的表格的相關(guān)信息,為了日后數(shù)據(jù)庫(kù)的更新更加方便 ,我們可以用一個(gè)專門的類保存數(shù)據(jù)庫(kù)的相關(guān)信息,以后如果要更新數(shù)據(jù)庫(kù)的話只需要該動(dòng)這個(gè)類就行了。這樣使得日后的操作更加方便。
新建一個(gè)Android工程:
在Src文件夾下新建一個(gè)包c(diǎn)om.example.databaseHelper:
在這個(gè)包中創(chuàng)建兩個(gè)類,首先我們來(lái)看第一個(gè)類DatabaseStatic.Java:
package com.example.databaseHelper; public class DatabaseStatic { public final static String DATABASE_NAME = "BookStore.db"; public final static int DATABASE_VERSION = 1; public final static String TABLE_NAME = "book"; public final static String BOOK_NAME = "bookName"; public final static String ID = "_id"; public final static String AUTHOR = "author"; public final static String PRICE = "price"; public final static String DATE = "sellData"; }
這個(gè)類中定義了數(shù)據(jù)庫(kù)名稱、版本、還有里面有一個(gè)名為“book”的表的相關(guān)信息,實(shí)現(xiàn)我們上面的意圖,接下來(lái)是這個(gè)包里面的另外一個(gè)類MyHelper.java:
package com.example.databaseHelper; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase.CursorFactory; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; import android.widget.Toast; /* * 在這個(gè)類的構(gòu)造函數(shù)里面我們調(diào)用了父類的構(gòu)造方法用來(lái)創(chuàng)建數(shù)據(jù)庫(kù)文 * 件,第二個(gè)構(gòu)造方法只是為了方便構(gòu)造(不用些那么多的參數(shù)) * 這個(gè)類繼承了 SQLiteOpenHelper 類,并且重寫了父類里面的 onCreate方法和 onUpgrade方法, * onCreate方法當(dāng)數(shù)據(jù)庫(kù)文件不存在的時(shí)候會(huì)被調(diào)用來(lái)創(chuàng)建一個(gè)新的數(shù) * 據(jù)庫(kù)文件(不懂的小伙伴可以百度一下) */ public class MyHelper extends SQLiteOpenHelper{ public static String CREATE_TABLE = "create table "+ DatabaseStatic.TABLE_NAME +"(" + DatabaseStatic.BOOK_NAME + " varchar(30), " + DatabaseStatic.ID + " Integer primary key autoincrement, " + DatabaseStatic.AUTHOR + " varchar(20) not null, " + DatabaseStatic.PRICE + " real)"; // 用于創(chuàng)建表的SQL語(yǔ)句 private Context myContext = null; public MyHelper(Context context, String name, CursorFactory factory, int version) { super(context, DatabaseStatic.DATABASE_NAME, null, DatabaseStatic.DATABASE_VERSION); } public MyHelper(Context context) { super(context, DatabaseStatic.DATABASE_NAME, null, DatabaseStatic.DATABASE_VERSION); myContext = context; } @Override public void onCreate(SQLiteDatabase db) { Log.i("UseDatabase", "創(chuàng)建數(shù)據(jù)庫(kù)"); Toast.makeText(myContext, "創(chuàng)建數(shù)據(jù)庫(kù)", Toast.LENGTH_SHORT).show(); db.execSQL(CREATE_TABLE); } @Override public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) { } }
當(dāng)要獲取數(shù)據(jù)庫(kù)對(duì)象時(shí)(通過(guò)SQLiteOPenHelper中自帶的方法getWriteableDatabase或者getReadableDatabase),如果數(shù)據(jù)庫(kù)文件不存在,這個(gè)類里面的onCreate方法會(huì)被調(diào)用來(lái)創(chuàng)建一個(gè)新的數(shù)據(jù)庫(kù)文件,如果數(shù)據(jù)庫(kù)文件已經(jīng)存在,那么onCreate方法將不會(huì)被調(diào)用
activity_main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/mainLayout" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:gravity="center_horizontal" tools:context=".MainActivity" > <Button android:id="@+id/buttonCreateDatabase" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="創(chuàng)建數(shù)據(jù)庫(kù)" /> <Button android:id="@+id/buttonInsertDatabase" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="插入數(shù)據(jù)"/> <Button android:id="@+id/buttonUpdateDatabase" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="更新數(shù)據(jù)"/> <Button android:id="@+id/buttonDeleteDatabase" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="刪除數(shù)據(jù)"/> <Button android:id="@+id/buttonQueryDatabase" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="顯示數(shù)據(jù)庫(kù)中 Book表中的所有數(shù)據(jù)"/> </LinearLayout>
一段布局代碼,主要是5個(gè)按鈕對(duì)應(yīng)5中對(duì)數(shù)據(jù)庫(kù)的操作:創(chuàng)建數(shù)據(jù)庫(kù)、插入數(shù)據(jù)、更新數(shù)據(jù)、刪除數(shù)據(jù)、顯示(查詢)數(shù)據(jù)。
那么最后是MainActivity.java:
import com.example.databaseHelper.DatabaseStatic; import com.example.databaseHelper.MyHelper; import android.os.Bundle; import android.app.Activity; import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.graphics.Color; import android.view.Menu; import android.view.View; import android.widget.Button; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends Activity { private MyHelper myHelper = null; private Button button = null; private SQLiteDatabase database = null; private static int bookSum = 0; TextView textView = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = new TextView(this); LinearLayout layout = (LinearLayout) findViewById(R.id.mainLayout); layout.addView(textView); button = (Button) findViewById(R.id.buttonCreateDatabase); button.setOnClickListener(listener); button = (Button) findViewById(R.id.buttonInsertDatabase); button.setOnClickListener(listener); button = (Button) findViewById(R.id.buttonUpdateDatabase); button.setOnClickListener(listener); button = (Button) findViewById(R.id.buttonDeleteDatabase); button.setOnClickListener(listener); button = (Button) findViewById(R.id.buttonQueryDatabase); button.setOnClickListener(listener); } private View.OnClickListener listener = new View.OnClickListener() { @Override public void onClick(View v) { switch(v.getId()) { case R.id.buttonCreateDatabase: createDatabase(); break; case R.id.buttonInsertDatabase: insertDatabase(); break; case R.id.buttonUpdateDatabase: updateDatabase(); break; case R.id.buttonDeleteDatabase: deleteDatabase(); break; case R.id.buttonQueryDatabase: searchDatabase(); break; } } }; private void createDatabase() // 創(chuàng)建或者打開數(shù)據(jù)庫(kù) { myHelper = new MyHelper(this); /* * 調(diào)用getWritabelDatabase方法或者 * getReadableDatabase方法時(shí),如果數(shù)據(jù)庫(kù)文 * 件中不存在(注意一個(gè)數(shù)據(jù)庫(kù)中可以存在多個(gè)表格), * 那么會(huì)回調(diào)MyHelper類的onCreate方法新建一個(gè)數(shù)據(jù)庫(kù)文 * 件并且在這個(gè)數(shù)據(jù)庫(kù)文件中新建一 * 個(gè)book表格 */ myHelper.getWritableDatabase(); } private void insertDatabase() // 向數(shù)據(jù)庫(kù)中插入新數(shù)據(jù) { if(myHelper == null) { myHelper = new MyHelper(this); } database = myHelper.getWritableDatabase(); ContentValues cV = new ContentValues(); cV.put(DatabaseStatic.BOOK_NAME, "C Language"); cV.put(DatabaseStatic.ID, ++bookSum); cV.put(DatabaseStatic.AUTHOR, "zhidian"); cV.put(DatabaseStatic.PRICE, 42.6); /* * 這個(gè)方法是留給不熟悉SQL語(yǔ)句的小伙伴用的,Android把 * SQLite的插入語(yǔ)句封裝了起來(lái), * 通過(guò) ContentValues 類的對(duì)象來(lái)保存數(shù)據(jù)庫(kù)中的數(shù)據(jù), * 于HashMap */ database.insert(DatabaseStatic.TABLE_NAME, null, cV); /* * 對(duì)應(yīng)的SQL語(yǔ)句: * database.execSQL("insert into " + DatabaseStatic.TABLENAME + " values(?, ?, ?, ?)", * new Object[]{"C Language", ++bookSum, "zhidian", 42.6}); * 或者是這個(gè): * database.execSQL("insert into " + DatabaseStatic.TABLENAME + "(" + * DatabaseStatic.BOOKNAME + ", " + DatabaseStatic.ID + ", " + * DatabaseStatic.AUTHOR + ", " + DatabaseStatic.PRICE + * ") values(?, ?, ?, ?)", new Object[]{"C Language", ++bookSum, "zhidian", 42.6}); * 這里將 ? 號(hào)理解成一個(gè)C語(yǔ)言里面的占位符,然后通過(guò) Object[] 數(shù)組中的內(nèi)容補(bǔ)全,下同 * 參數(shù)中的 Object[] 數(shù)組是一個(gè)通用的數(shù)組,里面的數(shù)據(jù)可以轉(zhuǎn)換為任意類型的數(shù)據(jù),通過(guò)這個(gè)完成不同數(shù)據(jù)類型變量之間的儲(chǔ)存 */ Toast.makeText(this, "插入數(shù)據(jù)成功", Toast.LENGTH_SHORT).show(); } private void updateDatabase() // 更新數(shù)據(jù) { if(myHelper == null) { myHelper = new MyHelper(this); } database = myHelper.getWritableDatabase(); ContentValues cV = new ContentValues(); cV.put(DatabaseStatic.AUTHOR, "xiaoming"); /* * 調(diào)用 update 方法,將書名為"C Language" 的書作者更新為 "xiaoming */ database.update(DatabaseStatic.TABLE_NAME, cV, DatabaseStatic.BOOK_NAME + "= ?", new String[]{"C Language"}); /* * 對(duì)應(yīng)的SQL語(yǔ)句: * database.execSQL("update " + DatabaseStatic.TABLENAME + " set " + DatabaseStatic.AUTHOR + * "= ? where " + DatabaseStatic.BOOKNAME + " = ?", new String[]{"xiaoming", "C Language"}); */ Toast.makeText(this, "數(shù)據(jù)更新成功", Toast.LENGTH_SHORT).show(); } private void deleteDatabase() // 數(shù)據(jù)庫(kù)中刪除數(shù)據(jù) { if(myHelper == null) { myHelper = new MyHelper(this); } database = myHelper.getWritableDatabase(); /* * 調(diào)用 delete 方法刪除數(shù)據(jù)庫(kù)中的數(shù)據(jù) * 對(duì)應(yīng)的SQL語(yǔ)句: * database.execSQL("delete from " + * DatabaseStatic.TABLE_NAME + " where " + * DatabaseStatic.BOOK_NAME + " = ?", new * String[]{"C Language"}); */ database.delete(DatabaseStatic.TABLE_NAME, DatabaseStatic.BOOK_NAME + " = ? ", new String[]{"C Language"}); Toast.makeText(this, "數(shù)據(jù)刪除成功", Toast.LENGTH_SHORT).show(); } private void searchDatabase() // 查詢數(shù)據(jù)庫(kù)中的數(shù)據(jù) { if(myHelper == null) { myHelper = new MyHelper(this); } database = myHelper.getWritableDatabase(); /* * 調(diào)用database的query方法,第一個(gè)參數(shù)是要查詢的表名, * 后面的參數(shù)是一些查詢的約束條件,對(duì)應(yīng)于SQL語(yǔ)句的一些參 * 數(shù), 這里全為null代表查詢表格中所有的數(shù)據(jù) * 查詢的結(jié)果返回一個(gè) Cursor對(duì)象 * 對(duì)應(yīng)的SQL語(yǔ)句: * Cursor cursor = database.rawQuery("select * from book", null); */ Cursor cursor = database.query(DatabaseStatic.TABLE_NAME, null, null, null, null, null, null); StringBuilder str = new StringBuilder(); if(cursor.moveToFirst()) // 顯示數(shù)據(jù)庫(kù)的內(nèi)容 { for(; !cursor.isAfterLast(); cursor.moveToNext()) // 獲取查詢游標(biāo)中的數(shù)據(jù) { str.append(cursor.getString(cursor.getColumnIndex(DatabaseStatic.ID)) + " "); str.append(cursor.getString(cursor.getColumnIndex(DatabaseStatic.BOOK_NAME)) + " "); str.append(cursor.getString(cursor.getColumnIndex(DatabaseStatic.AUTHOR)) + " "); str.append(cursor.getString(cursor.getColumnIndex(DatabaseStatic.PRICE)) + "\n"); } } cursor.close(); // 記得關(guān)閉游標(biāo)對(duì)象 if(str.toString().equals("")) { str.append("數(shù)據(jù)庫(kù)為空!"); textView.setTextColor(Color.RED); } else { textView.setTextColor(Color.BLACK); } textView.setText(str.toString()); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } }
MainActivity.java里面主要是實(shí)現(xiàn)了5個(gè)按鈕對(duì)應(yīng)的操作
SQLiteDatabase 類里面提供了對(duì)數(shù)據(jù)庫(kù)表格進(jìn)行插入、更新、刪除、查詢 的對(duì)應(yīng)API,用于給對(duì)SQL語(yǔ)句不熟悉的開發(fā)者使用,當(dāng)然我們還可以調(diào)用這個(gè)類里面的 execSQL 方法來(lái)直接執(zhí)行SQL語(yǔ)句中的插入、更改、刪除操作,用rawQuery 方法來(lái)執(zhí)行SQL語(yǔ)句的查詢語(yǔ)句。
Ok,整個(gè)工程的項(xiàng)目視圖(可能有些多余。。。):
好了,運(yùn)行一下:
先點(diǎn)擊“創(chuàng)建數(shù)據(jù)庫(kù)”按鈕:
程序中的數(shù)據(jù)庫(kù)文件都儲(chǔ)存在 /data/data/<包名>/databases文件中
運(yùn)行cmd(windows系統(tǒng))運(yùn)行abd調(diào)試工具(如果沒(méi)有將adb.exe加入環(huán)境變量中則需要寫出adb.exe的完整路徑)
輸入 adb shell
再輸入 cd /data/data/com.example.UseDataBase/databases進(jìn)入對(duì)應(yīng)儲(chǔ)存文件目錄
再輸入 ls 顯示文件中的子文件目錄,接下來(lái)我們就可以對(duì)數(shù)據(jù)庫(kù)文件進(jìn)行操作了:
輸入 sqlite3 數(shù)據(jù)庫(kù)名稱, 就可以對(duì)數(shù)據(jù)庫(kù)進(jìn)行操作了:
輸入 .table 來(lái)查看當(dāng)前數(shù)據(jù)庫(kù)文件中的表格目錄, 結(jié)果如下:
我們可以看到我們要?jiǎng)?chuàng)建的表格確實(shí)存在,證明我們的代碼確實(shí)創(chuàng)建了數(shù)據(jù)庫(kù)文件和里面對(duì)應(yīng)的表。
而我們注意到這里面還有另外一個(gè)android_metadata表,這個(gè)表是每個(gè)數(shù)據(jù)庫(kù)文件都會(huì)自動(dòng)生成的,不需要管。
接下來(lái)單擊“插入數(shù)據(jù)”按鈕:
之后 在控制臺(tái)中輸入 “select * from book;”,這個(gè)是查詢數(shù)據(jù)庫(kù)文件中的數(shù)據(jù)的SQL語(yǔ)句,不熟悉的小伙伴可以在網(wǎng)上查到一些教程
我們可以看到我們確實(shí)在book這張表中成功的插入了一條新的數(shù)據(jù)。
接下來(lái)單擊“更新數(shù)據(jù)”按鈕:
Ok,確實(shí)把書名為“C Language”的書的作者改為了 “xiaowei”,繼續(xù)單擊“刪除”按鈕:
使用 “select * from”語(yǔ)句查詢表中的所有數(shù)據(jù),并沒(méi)有看到有數(shù)據(jù),我們?cè)賳螕粢幌隆帮@示數(shù)據(jù)庫(kù)中book表中的所有數(shù)據(jù)”按鈕:
這樣看來(lái),數(shù)據(jù)庫(kù)中book表中的數(shù)據(jù)確實(shí)已經(jīng)被我們刪除了。
這里提一下SQLite數(shù)據(jù)庫(kù)操作的時(shí)候主要用到的數(shù)據(jù)類型:
整形:Integer、字符數(shù)組:varchar(10)、浮點(diǎn)數(shù):real、字符串文本:text。當(dāng)然SQLite還有很多的操作和支持的數(shù)據(jù)類型。
最后給出一些常用的SQL語(yǔ)句:
1、創(chuàng)建數(shù)據(jù)庫(kù)表:
create table 表名(參數(shù)1 數(shù)據(jù)類型 約數(shù)條件, 參數(shù)2 數(shù)據(jù)類型 約束條件…)
例:
create table person(_id Integer primary key autoincrement, name varchar(20), sex varchar(5) not null, age Integer)
2、插入數(shù)據(jù):
insert into 表名(參數(shù)1, 參數(shù)2…) values(參數(shù)1的值, 參數(shù)2的值…)
或者:
insert into 表名 values(參數(shù)1的值, 參數(shù)2的值)
例:
insert into person(_id, name, sex, age) values(1, “指點(diǎn)”, “男”, 19) insert into person values(1, “指點(diǎn)”, “男”, 19)
3、更新數(shù)據(jù):
update 表名 set 參數(shù)1 = 值, 參數(shù)2 = 值… where 條件1 and 條件2 or 條件3…
更新符合條件的所有數(shù)據(jù)
where后面的條件用 “and” 或者 “or”連接
例:
update person set _id = 0, age = 18 where _id = 1 and age<>19 // “<>”符號(hào)代表“不等于”
4、刪除數(shù)據(jù):
delete from 表名 where 條件1 and 條件2 or 條件3…
刪除符合條件的所有數(shù)據(jù)
例:
delete from person where _id > 0 and name = “指點(diǎn)”
前四個(gè)操作的SQL語(yǔ)句可用 execSQL 方法帶入?yún)?shù)執(zhí)行
5、查詢數(shù)據(jù):
select 參數(shù)1, 參數(shù)2… from 表名 where 條件1 and 條件2…
返回的是符合條件的所有的數(shù)據(jù)中的參數(shù)1、參數(shù)2…
例:
select _id, name, sex from person where name = “指點(diǎn)” or _id = 1
返回的是: 1、“指點(diǎn)”、“男”
注意查詢操作的SQL語(yǔ)句要用 rawQuery方法執(zhí)行,詳見(jiàn)代碼
Ok, 終于把SQLite 的基礎(chǔ)操作總結(jié)完了。這里所說(shuō)的只是SQLite操作的冰山一角,日后還得多多學(xué)習(xí)。
- Android SQLite數(shù)據(jù)庫(kù)增刪改查操作的使用詳解
- Android開發(fā)之SQLite的使用方法
- Android使用SQLite數(shù)據(jù)庫(kù)的簡(jiǎn)單實(shí)例
- android創(chuàng)建數(shù)據(jù)庫(kù)(SQLite)保存圖片示例
- Android登錄注冊(cè)功能 數(shù)據(jù)庫(kù)SQLite驗(yàn)證
- android中sqlite的按條件查找的小例子
- Android Studio連接SQLite數(shù)據(jù)庫(kù)的登錄注冊(cè)實(shí)現(xiàn)
- 深入Android SQLite 事務(wù)處理詳解
- Android--SQLite(增,刪,改,查)操作實(shí)例代碼
- Android?Studio中使用SQLite的操作方法
相關(guān)文章
AndroidStudio Gradle基于友盟的多渠道打包方法
這篇文章主要介紹了AndroidStudio Gradle基于友盟的多渠道打包方法,需要的朋友可以參考下2017-09-09Android開發(fā)自定義雙向SeekBar拖動(dòng)條控件
這篇文章主要為大家介紹了Android開發(fā)自定義雙向SeekBar拖動(dòng)條控件使用實(shí)例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-06-06android將Bitmap對(duì)象保存到SD卡中的方法
這篇文章主要介紹了android將Bitmap對(duì)象保存到SD卡中的方法,涉及Android讀寫SD卡數(shù)據(jù)的方法,需要的朋友可以參考下2015-04-04AndroidHttpClient詳解及調(diào)用示例
本文給大家介紹AndroidHttpClient結(jié)構(gòu)、使用方式及調(diào)用示例詳解,需要的朋友可以參考下2015-10-10Android學(xué)習(xí)之Flux架構(gòu)入門
Flux是Facebook在14年提出的一種Web前端架構(gòu),主要用來(lái)處理復(fù)雜的UI邏輯的一致性問(wèn)題(當(dāng)時(shí)是為了解決Web頁(yè)面的消息通知問(wèn)題)。接下來(lái)從其特點(diǎn)和使用上來(lái)介紹Flux架構(gòu)。本文主要目的是讓你對(duì)Flux的一個(gè)架構(gòu)大體面貌有個(gè)了解。2016-08-08Android開發(fā)使用WebView打造web app示例代碼
這篇文章主要介紹了Android開發(fā)使用WebView打造web app的關(guān)鍵示例代碼,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步2022-03-03Android使用Theme自定義Activity進(jìn)入退出動(dòng)畫的方法
這篇文章主要介紹了Android使用Theme自定義Activity進(jìn)入退出動(dòng)畫的方法,涉及Android的Activity屬性設(shè)置與資源操作技巧,需要的朋友可以參考下2016-07-07android實(shí)現(xiàn)定位與目的地的導(dǎo)航示例代碼
本篇文章主要介紹了android實(shí)現(xiàn)定位與目的地的導(dǎo)航示例代碼,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-02-02