日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 运维知识 > 数据库 >内容正文

数据库

安卓案例:利用SQLiteOpenHelper操作数据库及表

發(fā)布時間:2023/12/18 数据库 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 安卓案例:利用SQLiteOpenHelper操作数据库及表 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

安卓案例:利用SQLiteOpenHelper操作數(shù)據(jù)庫及表

一、運(yùn)行效果


二、涉及知識點
1、利用SQLiteOpenHelper類創(chuàng)建與升級數(shù)據(jù)庫
這個類是一個抽象類,我們必須繼承該類創(chuàng)建一個子類,實現(xiàn)里面的兩個抽象方法:
(1)public void?onCreate(SQLiteDatabase db);
(2)public void?onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion);

這兩個方法什么時候會調(diào)用呢?
如果數(shù)據(jù)庫不存在,那么就會調(diào)用onCreate方法來創(chuàng)建數(shù)據(jù)庫、表以及視圖。
如果數(shù)據(jù)庫存在但是沒有升級,什么事情也不做。
如果數(shù)據(jù)庫存在并且進(jìn)行了升級,那么就會調(diào)用onUpgrade方法來完成升級服務(wù)。

2、游標(biāo)與列表的綁定
數(shù)據(jù)表查詢的結(jié)果放在游標(biāo)集里,這作為數(shù)據(jù)源,如何把數(shù)據(jù)源和展示控件(ListView)綁定到一起呢?這就需要一個適配器——SimpleCursorAdapter(簡單游標(biāo)適配器)。

3、列表控件
4、上下文菜單?
5、對話框

三、實現(xiàn)步驟
1、創(chuàng)建安卓應(yīng)用SQLiteOpenHelperDemo


2、主布局資源文件activity_main.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
? ? xmlns:tools="http://schemas.android.com/tools"
? ? android:layout_width="match_parent"
? ? android:layout_height="match_parent"
? ? android:padding="15dp"
? ? tools:context="net.hw.sqlite_open_helper_demo.MainActivity">
? ??
? ? <ListView
? ? ? ? android:id="@+id/lv_student"
? ? ? ? android:layout_width="match_parent"
? ? ? ? android:layout_height="wrap_content"/>
? ??
</LinearLayout>
3、繼承SQLiteOpenHelper,創(chuàng)建自定義數(shù)據(jù)庫打開助手DBHelper


package net.hw.sqlite_open_helper_demo;
?
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.Toast;
?
/**
?* Created by Administrator on 2017/12/27.
?*/
?
public class DBHelper extends SQLiteOpenHelper {
? ? /**
? ? ?* 數(shù)據(jù)庫名
? ? ?*/
? ? private static final String DB_NAME = "student.db";
? ? /**
? ? ?* 數(shù)據(jù)庫版本號
? ? ?*/
? ? private static final int DB_VERSION = 1;
? ? /**
? ? ?* 表名
? ? ?*/
? ? private static final String TABLE_NAME = "student";
? ? /**
? ? ?* 上下文
? ? ?*/
? ? private Context context;
?
? ? /**
? ? ?* 構(gòu)造方法
? ? ?*
? ? ?* @param context
? ? ?*/
? ? public DBHelper(Context context) {
? ? ? ? super(context, DB_NAME, null, DB_VERSION);
? ? ? ? this.context = context;
? ? }
?
? ? /**
? ? ?* 創(chuàng)建方法:當(dāng)數(shù)據(jù)庫不存在時才調(diào)用
? ? ?*
? ? ?* @param db
? ? ?*/
? ? @Override
? ? public void onCreate(SQLiteDatabase db) {
? ? ? ? // 創(chuàng)建表
? ? ? ? createTable(db, TABLE_NAME);
? ? ? ? // 插入記錄
? ? ? ? insertRecords(db);
? ? }
?
? ? /**
? ? ?* 創(chuàng)建表
? ? ?*
? ? ?* @param tableName
? ? ?*/
? ? private void createTable(SQLiteDatabase db, String tableName) {
? ? ? ? // 定義SQL字符串
? ? ? ? String strSQL = "CREATE TABLE " + tableName + "(_id text, name text, gender text, age integer, major text)";
? ? ? ? try {
? ? ? ? ? ? // 執(zhí)行SQL,創(chuàng)建表
? ? ? ? ? ? db.execSQL(strSQL);
? ? ? ? ? ? // 提示用戶建表成功
? ? ? ? ? ? Toast.makeText(context, "恭喜,表【" + tableName + "】創(chuàng)建成功!", Toast.LENGTH_SHORT).show();
? ? ? ? } catch (SQLException e) {
? ? ? ? ? ? // 提示用戶建表失敗
? ? ? ? ? ? Toast.makeText(context, "遺憾,表【" + tableName + "】創(chuàng)建失敗!", Toast.LENGTH_SHORT).show();
? ? ? ? }
? ? }
?
? ? /**
? ? ?* 插入表記錄
? ? ?*
? ? ?* @param db
? ? ?*/
? ? private void insertRecords(SQLiteDatabase db) {
? ? ? ? // 創(chuàng)建內(nèi)容值對象
? ? ? ? ContentValues values = new ContentValues();
?
? ? ? ? // 通過鍵值對方式存放記錄信息
? ? ? ? values.put("_id", "1600001");
? ? ? ? values.put("name", "李云龍");
? ? ? ? values.put("gender", "男");
? ? ? ? values.put("age", 19);
? ? ? ? values.put("major", "軟件技術(shù)專業(yè)");
? ? ? ? // 調(diào)用db的插入方法,插入第1條記錄
? ? ? ? db.insert(TABLE_NAME, null, values);
?
? ? ? ? // 通過鍵值對方式存放記錄信息
? ? ? ? values.put("_id", "1600002");
? ? ? ? values.put("name", "張云紅");
? ? ? ? values.put("gender", "女");
? ? ? ? values.put("age", 18);
? ? ? ? values.put("major", "市場營銷專業(yè)");
? ? ? ? // 調(diào)用db的插入方法,插入第2條記錄
? ? ? ? db.insert(TABLE_NAME, null, values);
?
? ? ? ? // 通過鍵值對方式存放記錄信息
? ? ? ? values.put("_id", "1600003");
? ? ? ? values.put("name", "肖文燕");
? ? ? ? values.put("gender", "女");
? ? ? ? values.put("age", 20);
? ? ? ? values.put("major", "數(shù)字媒體專業(yè)");
? ? ? ? // 調(diào)用db的插入方法,插入第3條記錄
? ? ? ? db.insert(TABLE_NAME, null, values);
?
? ? ? ? // 通過鍵值對方式存放記錄信息
? ? ? ? values.put("_id", "1600004");
? ? ? ? values.put("name", "鄭小剛");
? ? ? ? values.put("gender", "男");
? ? ? ? values.put("age", 18);
? ? ? ? values.put("major", "軟件技術(shù)專業(yè)");
? ? ? ? // 調(diào)用db的插入方法,插入第4條記錄
? ? ? ? db.insert(TABLE_NAME, null, values);
?
? ? ? ? // 通過鍵值對方式存放記錄信息
? ? ? ? values.put("_id", "1600005");
? ? ? ? values.put("name", "唐雨涵");
? ? ? ? values.put("gender", "女");
? ? ? ? values.put("age", 20);
? ? ? ? values.put("major", "機(jī)械制造專業(yè)");
? ? ? ? // 調(diào)用db的插入方法,插入第5條記錄
? ? ? ? db.insert(TABLE_NAME, null, values);
?
? ? ? ? // 通過鍵值對方式存放記錄信息
? ? ? ? values.put("_id", "1600006");
? ? ? ? values.put("name", "王小丫");
? ? ? ? values.put("gender", "女");
? ? ? ? values.put("age", 20);
? ? ? ? values.put("major", "數(shù)字媒體專業(yè)");
? ? ? ? // 調(diào)用db的插入方法,插入第6條記錄
? ? ? ? db.insert(TABLE_NAME, null, values);
?
? ? ? ? // 通過鍵值對方式存放記錄信息
? ? ? ? values.put("_id", "1600007");
? ? ? ? values.put("name", "張廷玉");
? ? ? ? values.put("gender", "男");
? ? ? ? values.put("age", 18);
? ? ? ? values.put("major", "市場營銷專業(yè)");
? ? ? ? // 調(diào)用db的插入方法,插入第7條記錄
? ? ? ? db.insert(TABLE_NAME, null, values);
?
? ? ? ? // 通過鍵值對方式存放記錄信息
? ? ? ? values.put("_id", "1600008");
? ? ? ? values.put("name", "吳文霞");
? ? ? ? values.put("gender", "女");
? ? ? ? values.put("age", 20);
? ? ? ? values.put("major", "機(jī)械制造專業(yè)");
? ? ? ? // 調(diào)用db的插入方法,插入第8條記錄
? ? ? ? db.insert(TABLE_NAME, null, values);
?
? ? ? ? // 通過鍵值對方式存放記錄信息
? ? ? ? values.put("_id", "1600009");
? ? ? ? values.put("name", "王曉燕");
? ? ? ? values.put("gender", "女");
? ? ? ? values.put("age", 18);
? ? ? ? values.put("major", "數(shù)字媒體專業(yè)");
? ? ? ? // 調(diào)用db的插入方法,插入第9條記錄
? ? ? ? db.insert(TABLE_NAME, null, values);
?
? ? ? ? // 通過鍵值對方式存放記錄信息
? ? ? ? values.put("_id", "1600010");
? ? ? ? values.put("name", "董翔宇");
? ? ? ? values.put("gender", "男");
? ? ? ? values.put("age", 20);
? ? ? ? values.put("major", "市場營銷專業(yè)");
? ? ? ? // 調(diào)用db的插入方法,插入第10條記錄
? ? ? ? db.insert(TABLE_NAME, null, values);
? ? }
?
? ? /**
? ? ?* 查詢方法
? ? ?*
? ? ?* @param columns
? ? ?* @param selection
? ? ?* @param selectionArgs
? ? ?* @return
? ? ?*/
? ? public Cursor query(String[] columns, String selection, String[] selectionArgs) {
? ? ? ? // 獲取一個只讀數(shù)據(jù)庫
? ? ? ? SQLiteDatabase db = getReadableDatabase();
? ? ? ? // 執(zhí)行查詢方法,返回游標(biāo)
? ? ? ? return db.query(TABLE_NAME, columns, selection, selectionArgs, null, null, null);
? ? }
? ??
? ? public int delete(String whereClause, String[] whereArgs) {
? ? ? ? // 獲取一個可寫數(shù)據(jù)庫
? ? ? ? SQLiteDatabase db = getWritableDatabase();
? ? ? ? // 執(zhí)行刪除方法,返回刪除記錄數(shù)
? ? ? ? return db.delete(TABLE_NAME, whereClause, whereArgs); ? ??
? ? }
?
? ? /**
? ? ?* 更新方法(課堂練習(xí))
? ? ?*?
? ? ?* @param values
? ? ?* @param whereClause
? ? ?* @param whereArgs
? ? ?* @return
? ? ?*/
? ? public int update(ContentValues values, String whereClause, String[] whereArgs) {
? ? ? ? return 0;
? ? }
?
? ? /**
? ? ?* 插入方法(課堂練習(xí))
? ? ?*?
? ? ?* @param values
? ? ?* @return
? ? ?*/
? ? public int insert(ContentValues values) {
? ? ? ? return 0;
? ? }
?
? ? /**
? ? ?* 升級方法:當(dāng)數(shù)據(jù)庫升級時被調(diào)用
? ? ?*
? ? ?* @param sqLiteDatabase
? ? ?* @param i
? ? ?* @param i1
? ? ?*/
? ? @Override
? ? public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
? ? ? ? // 暫時不升級數(shù)據(jù)庫
? ? }
}
4、主界面類MainActivity


package net.hw.sqlite_open_helper_demo;
?
import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
?
public class MainActivity extends Activity {
? ? /**
? ? ?* 編輯菜單項標(biāo)識
? ? ?*/
? ? private static final int EDIT_MENU_ITEM = 1;
? ? /**
? ? ?* 刪除菜單項標(biāo)識
? ? ?*/
? ? private static final int DELETE_MENU_ITEM = 2;
? ? /**
? ? ?* 學(xué)生列表控件
? ? ?*/
? ? private ListView lvStudent;
? ? /**
? ? ?* 簡單游標(biāo)適配器
? ? ?*/
? ? private SimpleCursorAdapter adapter;
? ? /**
? ? ?* 游標(biāo)(數(shù)據(jù)源)
? ? ?*/
? ? private Cursor cursor;
? ? /**
? ? ?* 當(dāng)前列表項位置
? ? ?*/
? ? private int position;
? ? /**
? ? ?* 數(shù)據(jù)庫助手
? ? ?*/
? ? private DBHelper dbHelper;
?
? ? @Override
? ? protected void onCreate(Bundle savedInstanceState) {
? ? ? ? super.onCreate(savedInstanceState);
? ? ? ? // 利用布局資源文件設(shè)置用戶界面
? ? ? ? setContentView(R.layout.activity_main);
?
? ? ? ? // 通過資源標(biāo)識獲得控件實例
? ? ? ? lvStudent = (ListView) findViewById(R.id.lv_student);
?
? ? ? ? // 實例化數(shù)據(jù)庫助手
? ? ? ? dbHelper = new DBHelper(this);
?
? ? ? ? // 查詢?nèi)勘碛涗?br /> ? ? ? ? cursor = dbHelper.query(null, null, null);
?
? ? ? ? // 實例化簡單游標(biāo)適配器
? ? ? ? adapter = new SimpleCursorAdapter(
? ? ? ? ? ? ? ? this, // 參數(shù)1:上下文
? ? ? ? ? ? ? ? android.R.layout.simple_expandable_list_item_2, // 參數(shù)2:列表項模板
? ? ? ? ? ? ? ? cursor, // 參數(shù)3:游標(biāo)(數(shù)據(jù)源)
? ? ? ? ? ? ? ? new String[] {"name", "gender"}, // 參數(shù)4:字段列表
? ? ? ? ? ? ? ? new int[] {android.R.id.text1, android.R.id.text2}, // 參數(shù)5:控件標(biāo)識列表
? ? ? ? ? ? ? ? SimpleCursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER // 參數(shù)6:標(biāo)志(注冊內(nèi)容觀察者)
? ? ? ? );
?
? ? ? ? // 給列表控件設(shè)置適配器
? ? ? ? lvStudent.setAdapter(adapter);
? ? }
}
運(yùn)行程序,結(jié)果如下:


5、單擊列表項,彈出吐司,顯示該學(xué)生詳情
// 給列表控件注冊監(jiān)聽器
lvStudent.setOnItemClickListener(new AdapterView.OnItemClickListener() {
? ? @Override
? ? public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
? ? ? ? // 游標(biāo)定位到指定記錄
? ? ? ? cursor.moveToPosition(position);
? ? ? ??
? ? ? ? // 獲取當(dāng)前記錄各個字段值
? ? ? ? String _id = cursor.getString(cursor.getColumnIndex("_id"));
? ? ? ? String name = cursor.getString(cursor.getColumnIndex("name"));
? ? ? ? String gender = cursor.getString(cursor.getColumnIndex("gender"));
? ? ? ? int age = cursor.getInt(cursor.getColumnIndex("age"));
? ? ? ? String major = cursor.getString(cursor.getColumnIndex("major"));
? ? ? ??
? ? ? ? // 將各個字段值拼接成一個學(xué)生記錄信息
? ? ? ? StringBuilder builder = new StringBuilder();
? ? ? ? builder.append("學(xué)生詳細(xì)信息\n\n");
? ? ? ? builder.append("學(xué)號:" + _id + "\n");
? ? ? ? builder.append("姓名:" + name + "\n");
? ? ? ? builder.append("性別:" + gender + "\n");
? ? ? ? builder.append("年齡:" + age + "\n");
? ? ? ? builder.append("專業(yè):" + major + "\n");
? ? ? ? String studentInfo = builder.toString();
? ? ? ??
? ? ? ? // 通過吐司顯示學(xué)生信息
? ? ? ? Toast.makeText(MainActivity.this, studentInfo, Toast.LENGTH_SHORT).show();
? ? }
});
此時,運(yùn)行程序,單擊某一項:


6、創(chuàng)建上下文菜單
/**
?* 創(chuàng)建上下文菜單
?*?
?* @param menu
?* @param v
?* @param menuInfo
?*/
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
? ? super.onCreateContextMenu(menu, v, menuInfo);
? ? // 獲取適配器上下文菜單信息對象
? ? AdapterView.AdapterContextMenuInfo acmi = (AdapterView.AdapterContextMenuInfo) menuInfo;
? ??
? ? // 獲取列表項當(dāng)前位置
? ? position = acmi.position;
? ? // 游標(biāo)定位到指定記錄
? ? cursor.moveToPosition(position);
? ? // 獲取當(dāng)前記錄的姓名信息
? ? String name = cursor.getString(cursor.getColumnIndex("name"));
? ??
? ? // 添加上下文菜單項
? ? menu.add(1, EDIT_MENU_ITEM, 1, "編輯【" + name + "】記錄");
? ? menu.add(1, DELETE_MENU_ITEM, 2, "刪除【" + name + "】記錄");
? ? // 設(shè)置上下文菜單標(biāo)題行圖標(biāo)
? ? menu.setHeaderIcon(R.mipmap.ic_launcher);
? ? // 設(shè)置上下文菜單標(biāo)題行
? ? menu.setHeaderTitle("表記錄操作"); ? ? ? ?
}
7、在onCreate方法里給列表控件lvStudent注冊上下文菜單


此時,運(yùn)行程序,長按某一項:


8、完成刪除記錄功能
/**
?* 上下文菜單項選擇事件處理
?*?
?* @param item
?* @return
?*/
@Override
public boolean onContextItemSelected(MenuItem item) {
? ? switch (item.getItemId()) {
? ? ? ? case EDIT_MENU_ITEM:
? ? ? ? ? ? // TODO 課堂練習(xí)
? ? ? ? ? ? break;
? ? ? ? case DELETE_MENU_ITEM:
? ? ? ? ? ? // 定義警告對話框生成器
? ? ? ? ? ? AlertDialog.Builder builder = new AlertDialog.Builder(this);
? ? ? ? ? ? // 通過生成器設(shè)置,創(chuàng)建警告對話框
? ? ? ? ? ? builder.setIcon(R.mipmap.ic_launcher) // 設(shè)置圖標(biāo)
? ? ? ? ? ? ? ? ? ? .setTitle("刪除表記錄") // 設(shè)置標(biāo)題
? ? ? ? ? ? ? ? ? ? .setMessage("您是否要刪除當(dāng)前記錄?") // 設(shè)置正文
? ? ? ? ? ? ? ? ? ? .setPositiveButton("是", new DialogInterface.OnClickListener() {
? ? ? ? ? ? ? ? ? ? ? ? @Override
? ? ? ? ? ? ? ? ? ? ? ? public void onClick(DialogInterface dialogInterface, int i) {
? ? ? ? ? ? ? ? ? ? ? ? ? ? // 游標(biāo)定位到當(dāng)前記錄
? ? ? ? ? ? ? ? ? ? ? ? ? ? cursor.moveToPosition(position);
? ? ? ? ? ? ? ? ? ? ? ? ? ? // 獲取當(dāng)前記錄的_id
? ? ? ? ? ? ? ? ? ? ? ? ? ? String _id = cursor.getString(cursor.getColumnIndex("_id"));
? ? ? ? ? ? ? ? ? ? ? ? ? ? // 刪除當(dāng)前記錄
? ? ? ? ? ? ? ? ? ? ? ? ? ? int count = dbHelper.delete("_id = ?", new String[] {_id});
? ? ? ? ? ? ? ? ? ? ? ? ? ? // 判斷是否刪除成功
? ? ? ? ? ? ? ? ? ? ? ? ? ? if (count > 0) {
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? // 游標(biāo)執(zhí)行重查詢方法
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? cursor.requery();
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? // 刷新列表控件
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? lvStudent.deferNotifyDataSetChanged(); ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?
? ? ? ? ? ? ? ? ? ? ? ? ? ? } else {
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? Toast.makeText(MainActivity.this, "遺憾,記錄刪除失敗!", Toast.LENGTH_SHORT).show();
? ? ? ? ? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? ? ? }) // 設(shè)置肯定按鈕
? ? ? ? ? ? ? ? ? ? .setNegativeButton("否", null) // 設(shè)置否定按鈕
? ? ? ? ? ? ? ? ? ? .create() // 創(chuàng)建警告對話框
? ? ? ? ? ? ? ? ? ? .show(); // 顯示警告對話框
? ? ? ? ? ? break;
? ? }
? ? return true;
}
運(yùn)行程序,測試刪除功能:


單擊“刪除【李云龍】記錄”菜單項:


單擊【是】按鈕,看看“李云龍”還在不在?


9、完成編輯記錄功能(課堂練習(xí))

四、課后作業(yè)
對教學(xué)案例,完成添加記錄和查詢記錄功能。

系統(tǒng)主界面

編輯菜單:


查詢菜單:


排序菜單:


統(tǒng)計菜單:


關(guān)于菜單:


原文:https://blog.csdn.net/howard2005/article/details/79457374?
?

總結(jié)

以上是生活随笔為你收集整理的安卓案例:利用SQLiteOpenHelper操作数据库及表的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。