Android SQLite數(shù)據(jù)庫基本操作方法
程序的最主要的功能在于對數(shù)據(jù)進(jìn)行操作,通過對數(shù)據(jù)進(jìn)行操作來實(shí)現(xiàn)某個(gè)功能。而數(shù)據(jù)庫就是很重要的一個(gè)方面的,Android中內(nèi)置了小巧輕便,功能卻很強(qiáng)的一個(gè)數(shù)據(jù)庫–SQLite數(shù)據(jù)庫。那么就來看一下在Android程序中怎么去操作SQLite數(shù)據(jù)庫來實(shí)現(xiàn)一些需求的吧,仍然以一個(gè)小例子開始:
在創(chuàng)建Android項(xiàng)目之前,我們應(yīng)該想一下我們要定義的數(shù)據(jù)庫的相關(guān)信息和里面的表格的相關(guān)信息,為了日后數(shù)據(jù)庫的更新更加方便 ,我們可以用一個(gè)專門的類保存數(shù)據(jù)庫的相關(guān)信息,以后如果要更新數(shù)據(jù)庫的話只需要該動(dòng)這個(gè)類就行了。這樣使得日后的操作更加方便。
新建一個(gè)Android工程:
在Src文件夾下新建一個(gè)包c(diǎn)om.example.databaseHelper:
在這個(gè)包中創(chuàng)建兩個(gè)類,首先我們來看第一個(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ù)庫名稱、版本、還有里面有一個(gè)名為“book”的表的相關(guān)信息,實(shí)現(xiàn)我們上面的意圖,接下來是這個(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)造方法用來創(chuàng)建數(shù)據(jù)庫文
* 件,第二個(gè)構(gòu)造方法只是為了方便構(gòu)造(不用些那么多的參數(shù))
* 這個(gè)類繼承了 SQLiteOpenHelper 類,并且重寫了父類里面的
onCreate方法和 onUpgrade方法,
* onCreate方法當(dāng)數(shù)據(jù)庫文件不存在的時(shí)候會被調(diào)用來創(chuàng)建一個(gè)新的數(shù)
* 據(jù)庫文件(不懂的小伙伴可以百度一下)
*/
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語句
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ù)庫");
Toast.makeText(myContext, "創(chuàng)建數(shù)據(jù)庫", Toast.LENGTH_SHORT).show();
db.execSQL(CREATE_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
}
}
當(dāng)要獲取數(shù)據(jù)庫對象時(shí)(通過SQLiteOPenHelper中自帶的方法getWriteableDatabase或者getReadableDatabase),如果數(shù)據(jù)庫文件不存在,這個(gè)類里面的onCreate方法會被調(diào)用來創(chuàng)建一個(gè)新的數(shù)據(jù)庫文件,如果數(shù)據(jù)庫文件已經(jīng)存在,那么onCreate方法將不會被調(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ù)庫" /> <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ù)庫中 Book表中的所有數(shù)據(jù)"/> </LinearLayout>
一段布局代碼,主要是5個(gè)按鈕對應(yīng)5中對數(shù)據(jù)庫的操作:創(chuàng)建數(shù)據(jù)庫、插入數(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ù)庫
{
myHelper = new MyHelper(this);
/*
* 調(diào)用getWritabelDatabase方法或者
* getReadableDatabase方法時(shí),如果數(shù)據(jù)庫文
* 件中不存在(注意一個(gè)數(shù)據(jù)庫中可以存在多個(gè)表格),
* 那么會回調(diào)MyHelper類的onCreate方法新建一個(gè)數(shù)據(jù)庫文
* 件并且在這個(gè)數(shù)據(jù)庫文件中新建一
* 個(gè)book表格
*/
myHelper.getWritableDatabase();
}
private void insertDatabase() // 向數(shù)據(jù)庫中插入新數(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語句的小伙伴用的,Android把
* SQLite的插入語句封裝了起來,
* 通過 ContentValues 類的對象來保存數(shù)據(jù)庫中的數(shù)據(jù),
* 于HashMap
*/
database.insert(DatabaseStatic.TABLE_NAME, null, cV);
/*
* 對應(yīng)的SQL語句:
* 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});
* 這里將 ? 號理解成一個(gè)C語言里面的占位符,然后通過 Object[] 數(shù)組中的內(nèi)容補(bǔ)全,下同
* 參數(shù)中的 Object[] 數(shù)組是一個(gè)通用的數(shù)組,里面的數(shù)據(jù)可以轉(zhuǎn)換為任意類型的數(shù)據(jù),通過這個(gè)完成不同數(shù)據(jù)類型變量之間的儲存
*/
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"});
/*
* 對應(yīng)的SQL語句:
* 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ù)庫中刪除數(shù)據(jù)
{
if(myHelper == null)
{
myHelper = new MyHelper(this);
}
database = myHelper.getWritableDatabase();
/*
* 調(diào)用 delete 方法刪除數(shù)據(jù)庫中的數(shù)據(jù)
* 對應(yīng)的SQL語句:
* 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ù)庫中的數(shù)據(jù)
{
if(myHelper == null)
{
myHelper = new MyHelper(this);
}
database = myHelper.getWritableDatabase();
/*
* 調(diào)用database的query方法,第一個(gè)參數(shù)是要查詢的表名,
* 后面的參數(shù)是一些查詢的約束條件,對應(yīng)于SQL語句的一些參
* 數(shù), 這里全為null代表查詢表格中所有的數(shù)據(jù)
* 查詢的結(jié)果返回一個(gè) Cursor對象
* 對應(yīng)的SQL語句:
* 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ù)庫的內(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)對象
if(str.toString().equals(""))
{
str.append("數(shù)據(jù)庫為空!");
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è)按鈕對應(yīng)的操作
SQLiteDatabase 類里面提供了對數(shù)據(jù)庫表格進(jìn)行插入、更新、刪除、查詢 的對應(yīng)API,用于給對SQL語句不熟悉的開發(fā)者使用,當(dāng)然我們還可以調(diào)用這個(gè)類里面的 execSQL 方法來直接執(zhí)行SQL語句中的插入、更改、刪除操作,用rawQuery 方法來執(zhí)行SQL語句的查詢語句。
Ok,整個(gè)工程的項(xiàng)目視圖(可能有些多余。。。):

好了,運(yùn)行一下:
先點(diǎn)擊“創(chuàng)建數(shù)據(jù)庫”按鈕:
程序中的數(shù)據(jù)庫文件都儲存在 /data/data/<包名>/databases文件中
運(yùn)行cmd(windows系統(tǒng))運(yùn)行abd調(diào)試工具(如果沒有將adb.exe加入環(huán)境變量中則需要寫出adb.exe的完整路徑)
輸入 adb shell
再輸入 cd /data/data/com.example.UseDataBase/databases進(jìn)入對應(yīng)儲存文件目錄
再輸入 ls 顯示文件中的子文件目錄,接下來我們就可以對數(shù)據(jù)庫文件進(jìn)行操作了:
輸入 sqlite3 數(shù)據(jù)庫名稱, 就可以對數(shù)據(jù)庫進(jìn)行操作了:
輸入 .table 來查看當(dāng)前數(shù)據(jù)庫文件中的表格目錄, 結(jié)果如下:
我們可以看到我們要?jiǎng)?chuàng)建的表格確實(shí)存在,證明我們的代碼確實(shí)創(chuàng)建了數(shù)據(jù)庫文件和里面對應(yīng)的表。
而我們注意到這里面還有另外一個(gè)android_metadata表,這個(gè)表是每個(gè)數(shù)據(jù)庫文件都會自動(dòng)生成的,不需要管。
接下來單擊“插入數(shù)據(jù)”按鈕:
之后 在控制臺中輸入 “select * from book;”,這個(gè)是查詢數(shù)據(jù)庫文件中的數(shù)據(jù)的SQL語句,不熟悉的小伙伴可以在網(wǎng)上查到一些教程
我們可以看到我們確實(shí)在book這張表中成功的插入了一條新的數(shù)據(jù)。
接下來單擊“更新數(shù)據(jù)”按鈕:
Ok,確實(shí)把書名為“C Language”的書的作者改為了 “xiaowei”,繼續(xù)單擊“刪除”按鈕:
使用 “select * from”語句查詢表中的所有數(shù)據(jù),并沒有看到有數(shù)據(jù),我們再單擊一下“顯示數(shù)據(jù)庫中book表中的所有數(shù)據(jù)”按鈕:
這樣看來,數(shù)據(jù)庫中book表中的數(shù)據(jù)確實(shí)已經(jīng)被我們刪除了。
這里提一下SQLite數(shù)據(jù)庫操作的時(shí)候主要用到的數(shù)據(jù)類型:
整形:Integer、字符數(shù)組:varchar(10)、浮點(diǎn)數(shù):real、字符串文本:text。當(dāng)然SQLite還有很多的操作和支持的數(shù)據(jù)類型。
最后給出一些常用的SQL語句:
1、創(chuàng)建數(shù)據(jù)庫表:
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 // “<>”符號代表“不等于”
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語句可用 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語句要用 rawQuery方法執(zhí)行,詳見代碼
Ok, 終于把SQLite 的基礎(chǔ)操作總結(jié)完了。這里所說的只是SQLite操作的冰山一角,日后還得多多學(xué)習(xí)。
- Android SQLite數(shù)據(jù)庫增刪改查操作的使用詳解
- Android開發(fā)之SQLite的使用方法
- Android使用SQLite數(shù)據(jù)庫的簡單實(shí)例
- android創(chuàng)建數(shù)據(jù)庫(SQLite)保存圖片示例
- Android登錄注冊功能 數(shù)據(jù)庫SQLite驗(yàn)證
- android中sqlite的按條件查找的小例子
- Android Studio連接SQLite數(shù)據(jù)庫的登錄注冊實(shí)現(xiàn)
- 深入Android SQLite 事務(wù)處理詳解
- Android--SQLite(增,刪,改,查)操作實(shí)例代碼
- Android?Studio中使用SQLite的操作方法
相關(guān)文章
Android ndk獲取手機(jī)內(nèi)部存儲卡的根目錄方法
今天小編就為大家分享一篇Android ndk獲取手機(jī)內(nèi)部存儲卡的根目錄方法,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-08-08
Android利用CursorLoader實(shí)現(xiàn)短信驗(yàn)證碼自動(dòng)填寫
這篇文章主要為大家詳細(xì)介紹了Android利用CursorLoader實(shí)現(xiàn)短信驗(yàn)證碼自動(dòng)填寫的相關(guān)資料,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-11-11
Android調(diào)節(jié)屏幕亮度實(shí)現(xiàn)代碼
這篇文章主要介紹了Android調(diào)節(jié)屏幕亮度實(shí)現(xiàn)代碼,調(diào)節(jié)屏幕亮度時(shí),先設(shè)置當(dāng)前activity亮度,再并保存為系統(tǒng)亮度即可,本文分別給出兩個(gè)步驟的實(shí)現(xiàn)代碼,需要的朋友可以參考下2015-05-05
Kotlin示例講解標(biāo)準(zhǔn)函數(shù)with與run和apply的使用
Kotlin的標(biāo)準(zhǔn)函數(shù)是指 Standard.kt 文件中定義的函數(shù),任何Kotlin代碼都可以自由地調(diào)用所有的標(biāo)準(zhǔn)函數(shù)。文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧2022-08-08
Android 在 res/layout 文件夾 下創(chuàng)建一個(gè) 子文件夾實(shí)例
這篇文章主要介紹了Android 在 res/layout 文件夾 下創(chuàng)建一個(gè) 子文件夾實(shí)例,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-03-03
基于Flutter實(shí)現(xiàn)多邊形和多角星組件
開發(fā)中,免不了會用到多邊形、多角星等圖案,比較常用的多邊形比如雷達(dá)圖、多角星比如評價(jià)星級的五角星等,本文章就使用Flutter繪制封裝一個(gè)這樣的組件,需要的可以參考一下2022-05-05
Android 自定義view模板并實(shí)現(xiàn)點(diǎn)擊事件的回調(diào)
這篇文章主要介紹了Android 自定義view模板并實(shí)現(xiàn)點(diǎn)擊事件的回調(diào)的相關(guān)資料,需要的朋友可以參考下2017-01-01
Android實(shí)現(xiàn)捕獲TextView超鏈接的方法
這篇文章主要介紹了Android實(shí)現(xiàn)捕獲TextView超鏈接的方法,涉及Android查找TextView中超鏈接的相關(guān)實(shí)現(xiàn)技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-10-10

