Android SQLite教程含代碼

Android SQLite教程

SQLite 是一個 開源的關(guān)系型數(shù)據(jù)庫 即用于在Android設(shè)備上執(zhí)行數(shù)據(jù)庫操作,如存儲、操作或檢索持久數(shù)據(jù)。愛掏網(wǎng) - it200.com

它被默認嵌入到Android中,因此無需執(zhí)行任何數(shù)據(jù)庫設(shè)置或管理任務(wù)。愛掏網(wǎng) - it200.com

在這里,我們將看到使用SQLite存儲和獲取數(shù)據(jù)的示例。愛掏網(wǎng) - it200.com數(shù)據(jù)顯示在logcat中。愛掏網(wǎng) - it200.com要在下一個頁面上顯示數(shù)據(jù)在下拉列表或列表視圖上,請轉(zhuǎn)到下一頁。愛掏網(wǎng) - it200.com

SQLiteOpenHelper 類提供了使用SQLite數(shù)據(jù)庫的功能。愛掏網(wǎng) - it200.com

android.database.sqlite.SQLiteOpenHelper類用于數(shù)據(jù)庫的創(chuàng)建和版本管理。愛掏網(wǎng) - it200.com要執(zhí)行任何數(shù)據(jù)庫操作,您必須提供SQLiteOpenHelper類的 onCreate()onUpgrade() 方法的實現(xiàn)。愛掏網(wǎng) - it200.com

SQLiteOpenHelper類的構(gòu)造函數(shù)

SQLiteOpenHelper類有兩個構(gòu)造函數(shù)。愛掏網(wǎng) - it200.com

構(gòu)造函數(shù) 描述
SQLiteOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) 創(chuàng)建、打開和管理數(shù)據(jù)庫的對象。愛掏網(wǎng) - it200.com
SQLiteOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version, DatabaseErrorHandler errorHandler) 創(chuàng)建、打開和管理數(shù)據(jù)庫的對象。愛掏網(wǎng) - it200.com它指定了錯誤處理程序。愛掏網(wǎng) - it200.com

SQLiteOpenHelper類的方法

SQLiteOpenHelper類中有許多方法。愛掏網(wǎng) - it200.com以下是其中一些:

方法 描述
public abstract void onCreate(SQLiteDatabase db) 在數(shù)據(jù)庫第一次創(chuàng)建時調(diào)用,僅調(diào)用一次。愛掏網(wǎng) - it200.com
public abstract void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) 在數(shù)據(jù)庫需要升級時調(diào)用。愛掏網(wǎng) - it200.com
public synchronized void close () 關(guān)閉數(shù)據(jù)庫對象。愛掏網(wǎng) - it200.com
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) 在數(shù)據(jù)庫需要降級時調(diào)用。愛掏網(wǎng) - it200.com

SQLiteDatabase class

它包含了對sqlite數(shù)據(jù)庫執(zhí)行的方法,例如創(chuàng)建、更新、刪除、選擇等。愛掏網(wǎng) - it200.com

SQLiteDatabase類的方法

SQLiteDatabase類中有許多方法。愛掏網(wǎng) - it200.com其中一些如下:

方法 描述
void execSQL(String sql) 執(zhí)行非選擇查詢的sql語句。愛掏網(wǎng) - it200.com
long insert(String table, String nullColumnHack, ContentValues values) 在數(shù)據(jù)庫上插入一條記錄。愛掏網(wǎng) - it200.comtable指定表名,nullColumnHack不允許完全為空的值。愛掏網(wǎng) - it200.com如果第二個參數(shù)為空,android將在values為空時保存空值。愛掏網(wǎng) - it200.com第三個參數(shù)指定要存儲的值。愛掏網(wǎng) - it200.com
int update(String table, ContentValues values, String whereClause, String[] whereArgs) 更新一行。愛掏網(wǎng) - it200.com
Cursor query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy) 返回結(jié)果集的游標。愛掏網(wǎng) - it200.com

Android SQLite數(shù)據(jù)庫示例

讓我們看一個簡單的Android SQLite數(shù)據(jù)庫示例。愛掏網(wǎng) - it200.com

package example.javatpoint.com.sqlitetutorial;

public class Contact {
    int _id;
    String _name;
    String _phone_number;
    public Contact(){   }
    public Contact(int id, String name, String _phone_number){
        this._id = id;
        this._name = name;
        this._phone_number = _phone_number;
    }

    public Contact(String name, String _phone_number){
        this._name = name;
        this._phone_number = _phone_number;
    }
    public int getID(){
        return this._id;
    }

    public void setID(int id){
        this._id = id;
    }

    public String getName(){
        return this._name;
    }

    public void setName(String name){
        this._name = name;
    }

    public String getPhoneNumber(){
        return this._phone_number;
    }

    public void setPhoneNumber(String phone_number){
        this._phone_number = phone_number;
    }
}

現(xiàn)在,讓我們創(chuàng)建一個擴展SQLiteOpenHelper類并提供其方法實現(xiàn)的數(shù)據(jù)庫處理程序類。愛掏網(wǎng) - it200.com

package example.javatpoint.com.sqlitetutorial;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.ArrayList;
import java.util.List;


public class DatabaseHandler extends SQLiteOpenHelper {
    private static final int DATABASE_VERSION = 1;
    private static final String DATABASE_NAME = "contactsManager";
    private static final String TABLE_CONTACTS = "contacts";
    private static final String KEY_ID = "id";
    private static final String KEY_NAME = "name";
    private static final String KEY_PH_NO = "phone_number";

    public DatabaseHandler(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        //3rd argument to be passed is CursorFactory instance
    }

    // Creating Tables
    @Override
    public void onCreate(SQLiteDatabase db) {
        String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
                + KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
                + KEY_PH_NO + " TEXT" + ")";
        db.execSQL(CREATE_CONTACTS_TABLE);
    }

    // Upgrading database
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // Drop older table if existed
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);

        // Create tables again
        onCreate(db);
    }

    // code to add the new contact
    void addContact(Contact contact) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(KEY_NAME, contact.getName()); // Contact Name
        values.put(KEY_PH_NO, contact.getPhoneNumber()); // Contact Phone

        // Inserting Row
        db.insert(TABLE_CONTACTS, null, values);
        //2nd argument is String containing nullColumnHack
        db.close(); // Closing database connection
    }

    // code to get the single contact
    Contact getContact(int id) {
        SQLiteDatabase db = this.getReadableDatabase();

        Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
                        KEY_NAME, KEY_PH_NO }, KEY_ID + "=?",
                new String[] { String.valueOf(id) }, null, null, null, null);
        if (cursor != null)
            cursor.moveToFirst();

        Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
                cursor.getString(1), cursor.getString(2));
        // return contact
        return contact;
    }

    // code to get all contacts in a list view
    public List getAllContacts() {
        List contactList = new ArrayList();
        // Select All Query
        String selectQuery = "SELECT  * FROM " + TABLE_CONTACTS;

        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                Contact contact = new Contact();
                contact.setID(Integer.parseInt(cursor.getString(0)));
                contact.setName(cursor.getString(1));
                contact.setPhoneNumber(cursor.getString(2));
                // Adding contact to list
                contactList.add(contact);
            } while (cursor.moveToNext());
        }

        // return contact list
        return contactList;
    }

    // code to update the single contact
    public int updateContact(Contact contact) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(KEY_NAME, contact.getName());
        values.put(KEY_PH_NO, contact.getPhoneNumber());

        // updating row
        return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
                new String[] { String.valueOf(contact.getID()) });
    }

    // Deleting single contact
    public void deleteContact(Contact contact) {
        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(TABLE_CONTACTS, KEY_ID + " = ?",
                new String[] { String.valueOf(contact.getID()) });
        db.close();
    }

    // Getting contacts Count
    public int getContactsCount() {
        String countQuery = "SELECT  * FROM " + TABLE_CONTACTS;
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(countQuery, null);
        cursor.close();

        // return count
        return cursor.getCount();
    }

}
package example.javatpoint.com.sqlitetutorial;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        DatabaseHandler db = new DatabaseHandler(this);

        // Inserting Contacts
        Log.d("Insert: ", "Inserting ..");
        db.addContact(new Contact("Ravi", "9100000000"));
        db.addContact(new Contact("Srinivas", "9199999999"));
        db.addContact(new Contact("Tommy", "9522222222"));
        db.addContact(new Contact("Karthik", "9533333333"));

        // Reading all contacts
        Log.d("Reading: ", "Reading all contacts..");
        List contacts = db.getAllContacts();

        for (Contact cn : contacts) {
            String log = "Id: " + cn.getID() + " ,Name: " + cn.getName() + " ,Phone: " +
                    cn.getPhoneNumber();
            // Writing Contacts to log
            Log.d("Name: ", log);
        }
    }
}

輸出:

如何在Android Studio中查看存儲在SQLite中的數(shù)據(jù)?

按照以下步驟查看存儲在Android SQLite中的數(shù)據(jù)庫及其數(shù)據(jù):

  • 打開文件瀏覽器。愛掏網(wǎng) - it200.com
  • 進入data目錄下的data目錄。愛掏網(wǎng) - it200.com
  • 搜索您的應(yīng)用程序包名稱。愛掏網(wǎng) - it200.com
  • 在您的應(yīng)用程序包中進入databases目錄,您將找到您的數(shù)據(jù)庫(contactsManager)。愛掏網(wǎng) - it200.com
  • 將您的數(shù)據(jù)庫(contactsManager)保存在任何您喜歡的位置。愛掏網(wǎng) - it200.com
  • 下載任何SqLite瀏覽器插件或工具(在我的情況下是DB Browser for SQLite)。愛掏網(wǎng) - it200.com
  • 啟動DB Browser for SQLite并打開您的數(shù)據(jù)庫(contactsManager)。愛掏網(wǎng) - it200.com
  • 轉(zhuǎn)到瀏覽數(shù)據(jù) -> 選擇您的表格(contacts),您將看到存儲的數(shù)據(jù)。愛掏網(wǎng) - it200.com

聲明:所有內(nèi)容來自互聯(lián)網(wǎng)搜索結(jié)果,不保證100%準確性,僅供參考。如若本站內(nèi)容侵犯了原著者的合法權(quán)益,可聯(lián)系我們進行處理。
發(fā)表評論
更多 網(wǎng)友評論0 條評論)
暫無評論

返回頂部

主站蜘蛛池模板: 日本三级欧美三级| 菠萝菠萝蜜在线免费视频| 毛片免费全部无码播放| 天天干视频在线观看| 免费在线观看视频| 一本大道加勒比久久| 精品熟女碰碰人人a久久| 成视频年人黄网站免费视频| 国产乱偷国产偷高清| 久久久精品波多野结衣| 边摸边吃奶边做爽免费视频网站| 日韩免费高清一级毛片在线| 国产无卡一级毛片aaa| 久久精品国产清自在天天线| 国产精品视频h| 日韩三级中文字幕| 国产亚洲情侣一区二区无| 久久久久久久99精品免费观看| 色婷婷综合久久久| 成人免费视频网站www| 午夜精品久久久久久中宇| 一区二区日韩精品中文字幕| 第272章推倒孕妇秦| 天堂√在线官网| 亚洲爆乳少妇无码激情| 最新浮力影院地址第一页| 极品少妇被猛的白浆直喷白浆| 国产小视频91| 中文字幕视频一区| 精品国产一区二区三区久久| 天堂中文8资源在线8| 亚洲日本一区二区三区在线| 视频免费在线观看| 日韩亚洲欧美综合| 国产三级精品三级在专区| 中文字幕乱码人妻综合二区三区| 精品一区中文字幕| 在线jlzzjlzz免费播放| 亚洲伊人tv综合网色| 香港一级毛片免费看| 成在线人免费无码高潮喷水|