SQLiteDataBase數據庫

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:orientation="vertical"><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:orientation="horizontal"><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:text="姓名:" /><EditTextandroid:id="@+id/etc_name"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_marginLeft="50px" /></LinearLayout><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:orientation="horizontal"><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:text="班級:" /><EditTextandroid:id="@+id/etc_class"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_marginLeft="50px" /></LinearLayout><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:orientation="horizontal"><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:text="學號:" /><EditTextandroid:id="@+id/etc_id"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_marginLeft="50px" /></LinearLayout><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:orientation="horizontal"><Buttonandroid:id="@+id/btn_add"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_weight="1"android:text="添加數據"android:textAlignment="center" /><Buttonandroid:id="@+id/btn_show"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_weight="1"android:text="全部顯示"android:textAlignment="center" /><Buttonandroid:id="@+id/btn_clr"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_weight="1"android:text="清除數據"android:textAlignment="center" /><Buttonandroid:id="@+id/btn_del"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_weight="1"android:text="全部刪除"android:textAlignment="center" /></LinearLayout><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:orientation="horizontal"><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:text="ID:" /><EditTextandroid:id="@+id/etc_id2"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_weight="2" /></LinearLayout><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:orientation="horizontal"><Buttonandroid:id="@+id/btn_del_id"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_weight="1"android:text="ID刪除"android:textAlignment="center" /><Buttonandroid:id="@+id/btn_show_id"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_weight="1"android:text="ID查詢"android:textAlignment="center" /><Buttonandroid:id="@+id/btn_update_id"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_weight="1"android:text="ID更新"android:textAlignment="center" /></LinearLayout><TextViewandroid:id="@+id/txt_end"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="" /><ListViewandroid:id="@+id/list"android:layout_width="match_parent"android:layout_height="wrap_content"/></LinearLayout>
People.java
package com.example.exp6;public class People {public int ID = -1;public String Name;public String Class;public String Number;//重載toString方法  返回值String類型@Overridepublic String toString(){String result = "";result += "ID:" + this.ID + ",";result += "姓名:" + this.Name + ",";result += "班級:" + this.Class + ", ";result += "學號:" + this.Number;return result;}
}
?DBAdapter.java
package com.example.exp6;
import android.annotation.SuppressLint;
import android.content.*;
import android.database.Cursor;
import android.database.DatabaseErrorHandler;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;import androidx.annotation.Nullable;//對數據庫進行操作的類
public class DBAdapter {private static final String DB_NAME = "student.db";   //數據庫名稱private static final String DB_TABLE = "peopleinfo";  //表名private static final int DB_VERSION = 1;              //數據庫版本public static final String KEY_ID = "_id";            //數據庫表的屬性名稱public static final String KEY_NAME = "name";public static final String KEY_CLASS = "class";public static final String KEY_NUMBER = "number";private SQLiteDatabase db;              //數據庫的實例dbprivate final Context context;          //Context的實例化private DBOpenHelper dbOpenHelper;      //幫助類的實例化 dbOpenHelper//內部類:對幫助類 構建//繼承SQLiteOpenHelper//必須重載onCreate和onUpgrade方法private static class DBOpenHelper extends SQLiteOpenHelper {//幫助類的構造函數 -- 4個參數//Code -> SQLiteOpenHelper 即可成功插入該構造函數public DBOpenHelper(@Nullable Context context, @Nullable String name,SQLiteDatabase.CursorFactory factory, int version) {super(context, name, factory, version);}//static常量字符串--創建表的 sql 命令//create table peopleinfo("id integer primary key autoincrement,name text not null,// class text not null,number text not null")private static final String DB_CREATE = "create table " +DB_TABLE + " (" + KEY_ID + " integer primary key autoincrement, " +KEY_NAME + " text not null, " + KEY_CLASS + " text not null," +KEY_NUMBER + " text not null);";//重載幫助類onCreate方法//1個參數SQLiteDatabase類型@Overridepublic void onCreate(SQLiteDatabase sqLiteDatabase) {//execSQL()方法 1個String類型的 sql 建表命令sqLiteDatabase.execSQL(DB_CREATE);}//重載幫助類onUpdate方法//一般在升級的時候被調用//刪除舊的數據庫表 并將數據轉移到新版本的數據庫表//3個參數SQLiteDatabase類型、int i-舊版本號、int i1-新版本號@Overridepublic void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {//僅刪除原表后建立新表sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + DB_TABLE);onCreate(sqLiteDatabase);}}//對數據庫進行操作的類DBAdapter的構造//參數1個 Context類型public DBAdapter(Context _context) {context = _context;}//DBAdapter類的open方法//拋出異常!!!!public void open() throws SQLiteException {//幫助類實例化dbOpenHelper需要4個參數dbOpenHelper = new DBOpenHelper(context, DB_NAME,null, DB_VERSION);//調用getWritableDatabase方法try {db = dbOpenHelper.getWritableDatabase();} catch (SQLiteException ex) {db = dbOpenHelper.getReadableDatabase();}}//DBAdapter類的close方法public void close() {if (db != null) {db.close();db = null;}}//DBAdapter類的insert方法//參數1個:數據庫儲存的類型(本例是Peoplepublic long insert(People people) {//用ContentValues類型ContentValues newValues = new ContentValues();//在put的時候不需要put Key_ID!!!newValues.put(KEY_NAME, people.Name);newValues.put(KEY_CLASS, people.Class);newValues.put(KEY_NUMBER, people.Number);//返回值是新數據插入的位置 ID值//數據庫對象.insert方法//參數3個:表名 在null時的替換數據 ContentValues類型需要添加的數據return db.insert(DB_TABLE, null, newValues);}//DBAdapter類的deleteAllData方法//無參數public long deleteAllData() {//返回值是被刪除的數據的數量//參數3個:表名 刪除條件(刪除全部數據條件是null)return db.delete(DB_TABLE, null, null);}//DBAdapter類的deleteOneData方法//參數1個:long類型的id值public long deleteOneData(long id) {//返回值是被刪除的數據的數量//參數3個:表名 刪除條件(刪除形參給的id)return db.delete(DB_TABLE,  KEY_ID + "=" + id, null);}//DBAdapter類的UpdataOneData方法//參數2個:long類型的id值 和 People類型public long updateOneData(long id , People people){//更新和插入一樣用到了ContentValues類型ContentValues updateValues = new ContentValues();//同樣不需要放Key_IDupdateValues.put(KEY_NAME, people.Name);updateValues.put(KEY_CLASS, people.Class);updateValues.put(KEY_NUMBER, people.Number);//返回值是被更新的數據數量//參數4個 表明 ContentValues 更新條件string類型 nullreturn db.update(DB_TABLE, updateValues,  KEY_ID + "=" + id, null);}//private類型//DBAdapter類的ConvertToPeople方法//參數1個 Cursor類型//返回People數組//查詢需要基于該 ConvertToPeople 方法(應該是自定義方法?)@SuppressLint("Range")private People[] ConvertToPeople(Cursor cursor){//getCount方法返回查詢結果總行數int resultCounts = cursor.getCount();//行數為0||moveToFirst方法返回false返回結果為空if (resultCounts == 0 || !cursor.moveToFirst()){//該方法返回nullreturn null;}//新建resultCounts個People對象People[] peoples = new People[resultCounts];//循環 resultCounts次for (int i = 0 ; i<resultCounts; i++){peoples[i] = new People();peoples[i].ID = cursor.getInt(0);//根據 列屬性索引 得到 屬性值peoples[i].Name = cursor.getString(cursor.getColumnIndex(KEY_NAME));peoples[i].Class = cursor.getString(cursor.getColumnIndex(KEY_CLASS));peoples[i].Number = cursor.getString(cursor.getColumnIndex(KEY_NUMBER));//游標/指針下移cursor.moveToNext();}//返回People[]return peoples;}//查詢操作://DBAdapter類的getOneData方法//參數1個:long類型的id值public People[] getOneData(long id) {//query方法//參數7個(6String 1String[]):表名稱 屬性列-String[] 查詢條件//查詢條件是否使用通配符 分組條件 分組過濾條件 排序方式  后4個全是null//返回Cursor類型Cursor results =  db.query(DB_TABLE, new String[] { KEY_ID, KEY_NAME, KEY_CLASS, KEY_NUMBER},KEY_ID + "=" + id, null, null, null, null);//返回People[]return ConvertToPeople(results);}//DBAdapter類的getAllData方法public People[] getAllData() {//參數查詢條件為null  存在5個nullCursor results = db.query(DB_TABLE, new String[] { KEY_ID, KEY_NAME, KEY_CLASS, KEY_NUMBER},null, null, null, null, null);return ConvertToPeople(results);}}
MainActivity.java?
package com.example.exp6;import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import java.util.ArrayList;
import java.util.List;
import android.widget.ArrayAdapter;public class MainActivity extends AppCompatActivity {EditText etc_name,etc_class,etc_id,etc_id2;TextView txt_end;ListView listView;Button btn_add,btn_show,btn_clr,btn_del,btn_del_id,btn_show_id,btn_update_id;DBAdapter dbAdapter;SQLiteDatabase db;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);listView=findViewById(R.id.list);ArrayList<String> data=new ArrayList<String>();//數組適配器//實例化 參數3個ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,data);etc_name=findViewById(R.id.etc_name);etc_class=findViewById(R.id.etc_class);etc_id=findViewById(R.id.etc_id);btn_add=findViewById(R.id.btn_add);btn_show=findViewById(R.id.btn_show);btn_clr=findViewById(R.id.btn_clr);btn_del=findViewById(R.id.btn_del);btn_del_id=findViewById(R.id.btn_del_id);btn_show_id=findViewById(R.id.btn_show_id);btn_update_id= findViewById(R.id.btn_update_id);etc_id2=findViewById(R.id.etc_id2);txt_end=findViewById(R.id.txt_end);//處理數據庫的類的實例對象//參數1個 Context類型dbAdapter=new DBAdapter(this);//調用DBAdapter對象的 open 方法dbAdapter.open();btn_add.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {//將文本框中的內容用來創建對象PeoplePeople t=new People();t.Name=etc_name.getText().toString();t.Class=etc_class.getText().toString();t.Number=etc_id.getText().toString();//插入一個對象People//返回插入的位置idlong colunm=dbAdapter.insert(t);if (colunm == -1 ){txt_end.setText("添加過程錯誤!");} else {txt_end.setText("ID:"+String.valueOf(colunm)+"   姓名:"+t.Name+"   班級:"+t.Class+"   學號:"+t.Number);}}});btn_show.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {//調用得到數據庫中全部的信息People [] peoples =dbAdapter.getAllData();if (peoples == null){txt_end.setText("數據庫中沒有數據");return;}String t="數據庫:\n";for(int i=0;i<peoples.length;++i){t += peoples[i].toString()+"\n";}txt_end.setText(t);}});btn_clr.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {txt_end.setText("");}});btn_del.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {dbAdapter.deleteAllData();txt_end.setText("已刪除所有數據!");}});btn_del_id.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {int id=Integer.parseInt(etc_id2.getText().toString());//返回刪除的數據的數量//參數要求int類型的long result=dbAdapter.deleteOneData(id);String msg = "刪除ID為"+etc_id2.getText().toString()+"的數據" + (result>0?"成功":"失敗");txt_end.setText(msg);}});btn_show_id.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {int id=Integer.parseInt(etc_id2.getText().toString());//查找方法 參數id-int//返回值是People[]People people[]=dbAdapter.getOneData(id);if(people==null){txt_end.setText("Id為"+id+"的記錄不存在!");}else{//因為僅只查找了一條信息 所以是people[0]//并且在People類型中已經重載了函數toString()txt_end.setText("查詢成功:\n"+people[0].toString());}}});btn_update_id.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {int id=Integer.parseInt(etc_id2.getText().toString());People t=new People();t.Name=etc_name.getText().toString();t.Class=etc_class.getText().toString();t.Number=etc_id.getText().toString();//更新方法//參數2個 id-int people類型//返回值 被更新的數據數量long n=dbAdapter.updateOneData(id,t);if (n<0){txt_end.setText("更新過程錯誤!");}else{txt_end.setText("成功更新數據,"+String.valueOf(n)+"條");}}});}@Overrideprotected void onStop() {super.onStop();dbAdapter.close();}
}
結果

數據添加(朱迪&尼克狐尼克)

全部顯示?

ID刪除 (25-朱迪)

?ID查詢 (26)

ID更新 (26)?

全部刪除

全部顯示?

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/web/64611.shtml
繁體地址,請注明出處:http://hk.pswp.cn/web/64611.shtml
英文地址,請注明出處:http://en.pswp.cn/web/64611.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

k8s部署nginx+sshd實現文件上傳下載

要通過 nginx 和 sshd 實現文件的上傳和下載&#xff0c;通常的做法是結合 SSH 協議和 HTTP 協議&#xff0c;使用 nginx 提供 Web 服務器功能&#xff0c;同時使用 sshd&#xff08;即 SSH 服務&#xff09;來處理通過 SSH 協議進行的文件傳輸。 SSH 實現文件的上傳和下載&…

Golang 中 Goroutine 的調度

Golang 中 Goroutine 的調度 Golang 中的 Goroutine 是一種輕量級的線程&#xff0c;由 Go 運行時&#xff08;runtime&#xff09;自動管理。Goroutine 的調度基于 M:N 模型&#xff0c;即多個 Goroutine 可以映射到多個操作系統線程上執行。以下是詳細的調度過程和策略&…

clickhouse-backup配置及使用(Linux)

一、下載地址 Releases Altinity/clickhouse-backup GitHub 二、上傳到服務器解壓安裝 自行上傳至服務器&#xff0c;解壓命令&#xff1a; tar xvf clickhouse-backup-linux-amd64.tar.gz 三、創建軟連接 sudo ln -sv build/linux/amd64/clickhouse-backup /usr/local/bin/…

如何在群暉NAS上安裝并配置MySQL與phpMyAdmin遠程管理數據庫

文章目錄 前言1. 安裝MySQL2. 安裝phpMyAdmin3. 修改User表4. 本地測試連接MySQL5. 安裝cpolar內網穿透6. 配置MySQL公網訪問地址7. 配置MySQL固定公網地址8. 配置phpMyAdmin公網地址9. 配置phpmyadmin固定公網地址 前言 大家是不是經常遇到需要隨時隨地訪問自己數據的情況&am…

《向量數據庫指南》——Milvus Cloud 2.5:Sparse-BM25引領全文檢索新時代

Milvus Cloud BM25:重塑全文檢索的未來 在最新的Milvus Cloud 2.5版本中,我們自豪地引入了“全新”的全文檢索能力,這一創新不僅鞏固了Milvus Cloud在向量數據庫領域的領先地位,更為用戶提供了前所未有的靈活性和效率。作為大禹智庫的向量數據庫高級研究員,以及《向量數據…

SQL 總結

SQL 總結 引言 SQL(Structured Query Language,結構化查詢語言)是一種用于管理關系數據庫管理系統(RDBMS)的標準編程語言。自1974年首次提出以來,SQL已成為數據庫領域中不可或缺的一部分。它允許用戶執行各種操作,如查詢、更新、插入和刪除數據庫中的數據。本文旨在提…

ESP32-CAM開發板入門 (下載示例程序)

ESP32-CAM開發板例程使用 1、準備工作1.1、硬件準備1.2、軟件準備 2、選擇示例程序并錄入第一步 1、準備工作 1.1、硬件準備 1.2、軟件準備 Arduino IDE &#xff1a; 編程與寫入&#xff08;下載地址 https://www.arduino.cc/en/software&#xff09; 安裝好后將軟件設置到…

企業賦能是什么意思-國際數字影像產業園解讀

在當今競爭激烈的商業環境中&#xff0c;企業賦能已成為推動企業發展、提升競爭力的關鍵策略。國際數字影像產業園作為數字影像產業的重要集聚地&#xff0c;通過一系列創新舉措為入駐園區的我眾多企業賦能。那么&#xff0c;企業賦能究竟是什么意思呢&#xff1f; 企業賦能是…

混合并行訓練框架性能對比

混合并行訓練框架性能對比 1. 框架類型 DeepSpeed、Megatron - LM、Colossal - AI、SageMaker、Merak、FasterMoE、Tutel、Whale、Alpa、DAPPLE、Mesh - TensorFlow 2. 可用并行性(Available parallelisms) DNN framework(深度神經網絡框架)DP(數據并行,Data Parallelis…

客戶案例:基于慧集通集成平臺,打通屠宰管理系統與用友U8C 系統的全攻略

一、引言 本原型客戶成立于2014年&#xff0c;是一家集飼草種植、肉牛養殖、精深加工、冷鏈物流、餐飲服務于一體的大型農牧綜合體。公司下設三個子公司分別涵蓋農業、畜牧業、肉制品加工業與餐飲物流服務業。公司嚴格按照一二三產業融合發展要求&#xff0c;以肉牛產業化為支…

HTML5滑塊(Slider)

HTML5 的滑塊&#xff08;Slider&#xff09;控件允許用戶通過拖動滑塊來選擇數值。以下是如何實現一個簡單的滑塊組件的詳細說明。 HTML5 滑塊組件 1. 基本結構 使用 <input type"range"> 元素可以創建一個滑塊。下面是基本實現的代碼示例&#xff1a; <…

25. C++繼承 1 (繼承的概念與基礎使用, 繼承的復制兼容規則,繼承的作用域)

?上篇模板文章&#xff1a;24. C模板 2 (非類型模板參數&#xff0c;模板的特化與模板的分離編譯)-CSDN博客 ?本篇代碼&#xff1a;c學習 橘子真甜/c-learning-of-yzc - 碼云 - 開源中國 (gitee.com) ?標?是比較重要的部分 目錄 一. 繼承的基礎使用 1.1 繼承的格式 1.2 …

露營小程序搭建有哪些步驟?小程序里面可以找個露營搭子

露營不僅僅是走進大自然的旅程&#xff0c;它也成為了一種社交和體驗式的活動。隨著小程序的普及&#xff0c;露營活動也越來越多地開始在線上開展。通過搭建一個露營小程序&#xff0c;商家不僅可以為用戶提供更多的露營選擇&#xff0c;還可以幫助他們找到合適的露營搭子。那…

XIAO ESP32 S3網絡攝像頭——2視頻獲取

本文主要是使用XIAO Esp32 S3制作網絡攝像頭的第2步,獲取攝像頭圖像。 1、效果如下: 2、所需硬件 3、代碼實現 3.1硬件代碼: #include "WiFi.h" #include "WiFiClient.h" #include "esp_camera.h" #include "camera_pins.h"// 設…

記一次 dockerfile 的循環依賴錯誤

文章目錄 1. 寫在最前面1.1 具體循環依賴的例子 2. 報錯的位置2.1 代碼快速分析2.2 代碼總結2.3 關于 parser 的記錄 3. 碎碎念 1. 寫在最前面 筆者在使用 dockerfile 多階段構建的功能時&#xff0c;寫出了一個「circular dependency detected on stage: xx」的錯誤。 解決方…

AAAI 2025論文分享┆一種接近全監督的無訓練文檔信息抽取方法:SAIL(文中附代碼鏈接)

本推文詳細介紹了一篇上海交通大學樂心怡老師課題組被人工智能頂級會議AAAI 2025錄用的的最新論文《SAIL: Sample-Centric In-Context Learning for Document Information Extraction》。論文的第一作者為張金鈺。該論文提出了一種無需訓練的、以樣本為中心的、基于上下文學習的…

小程序信息收集(小迪網絡安全筆記~

免責聲明&#xff1a;本文章僅用于交流學習&#xff0c;因文章內容而產生的任何違法&未授權行為&#xff0c;與文章作者無關&#xff01;&#xff01;&#xff01; 附&#xff1a;完整筆記目錄~ ps&#xff1a;本人小白&#xff0c;筆記均在個人理解基礎上整理&#xff0c;…

pat 乙級1096 大美數

若正整數 N 可以整除它的 4 個不同正因數之和&#xff0c;則稱這樣的正整數為“大美數”。本題就要求你判斷任一給定的正整數是否是“大美數”。 輸入格式&#xff1a; 輸入在第一行中給出正整數 K&#xff08;≤10&#xff09;&#xff0c;隨后一行給出 K 個待檢測的、不超過…

C#封送類

封送類&#xff08;Marshaling classes&#xff09;在.NET框架中扮演著至關重要的角色&#xff0c;尤其是在托管代碼與非托管代碼之間進行數據交換時。封送過程涉及到將托管環境中的對象轉換為非托管環境中可以理解的形式&#xff0c;并且反之亦然。這一過程確保了兩種不同類型…

計算機體系結構期末考試

1、描述計算機系統性能評估的關鍵指標&#xff0c;并以SPEC CPU benchmark為例&#xff0c;討論如何使用幾何平均數與加權平均數對性能進行量化。此外&#xff0c;描述Amdahl定律并分析該定律的應用場景及其對性能優化的局限性 2、請對比RISC和CISC指令集架構的設計思想及優缺點…