Android SQLite數據庫的建立和增刪改查

Android SQLite數據庫的建立和增刪改查

在這裏插入圖片描述

話不多說,先上代碼

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:orientation="vertical"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/tv_query"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="沒有記錄"></TextView>
    <Button
        android:onClick="AddClick"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/Addstr"></Button>

    <Button
        android:onClick="updatedatabaseClick"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/UpdateDatabase"></Button>
    <Button
        android:onClick="DelClick"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/DelStr"></Button>
    <Button
        android:onClick="UpdataClick"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/UpdateStr"></Button>
    <Button
        android:onClick="QueryClick"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/QueryStr"></Button>

</LinearLayout>

strings.xml

<resources>
    <string name="app_name">class0422</string>
    <string name="Addstr">插入數據</string>

    <string name="Succstr">成功了</string>
    <string name="Failstr">失敗了</string>

    <string name="UpdateDatabase">升級數據庫</string>
    <string name="DelStr">刪除記錄</string>
    <string name="UpdateStr">修改記錄</string>
    <string name="QueryStr">查詢記錄</string>

</resources>

MainActivity.java(數據庫的建立和增刪改查操作)

package com.example.class0422;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import org.w3c.dom.Text;

import java.sql.SQLData;

public class MainActivity extends AppCompatActivity {

    MyDBHelper myDBHelper = null;
    SQLiteDatabase db = null;
    ContentValues contentValues= null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        myDBHelper = new MyDBHelper(this);
        //初始化並打開數據庫
        db = myDBHelper.getWritableDatabase();
        //關閉數據庫
        db.close();
    }

    public void AddClick(View view){
    	//初始化數據庫
        db = myDBHelper.getWritableDatabase();
        try{
            //第一種方法:用SQL字符串拼接
//            String Sqlstr = "insert into " + databasepublicstr.tableName+
//                    "(stunum,stuname,stuage) values('001','劉備','21')";
//            db.execSQL(Sqlstr);
            //第二種方法:用數組形式添加
//            String SqlStr = "insert into "+ databasepublicstr.tableName +"(stunum,stuname,stuage) values(?,?,?)";
//          String [] strArray = {"002","關羽","20"};
//           db.execSQL(SqlStr,strArray);
           //第三種方法:採用內置的方法
            contentValues = new ContentValues();
            contentValues.put("stunum","003");
            contentValues.put("stuname","張飛");
            contentValues.put("stuage","19");
            db.insert(databasepublicstr.tableName,null,contentValues);
            Toast.makeText(this,R.string.Succstr,Toast.LENGTH_SHORT).show();
        }catch (Exception e){
            e.printStackTrace();
            Toast.makeText(this,R.string.Failstr,Toast.LENGTH_SHORT).show();
        }
        finally {
            db.close();
        }
    }

    public  void updatedatabaseClick(View view){
        db = myDBHelper.getWritableDatabase();
        try{
//數據庫的更新操作            myDBHelper.onUpgrade(db,databasepublicstr.DB_Version,databasepublicstr.New_Version);
            Toast.makeText(this,R.string.Succstr,Toast.LENGTH_SHORT).show();
        }catch (Exception e){
            e.printStackTrace();
            Toast.makeText(this,R.string.Failstr,Toast.LENGTH_SHORT).show();
        }
        finally {
            db.close();
        }
    }

    public void DelClick(View view){
        db = myDBHelper.getWritableDatabase();
        try {
//            //方法1:拼接字符串
//            String SqlStr = "delete from "+databasepublicstr.tableName+" where stunum='004'";
//            db.execSQL(SqlStr);
//            //方法2:數組形式
//            String SqlStr = "delete from "+databasepublicstr.tableName+" where stunum=?";
//            String [] strings={"004"};
//            db.execSQL(SqlStr,strings);
            //方法3:ANDROID內置的del
            db.delete(databasepublicstr.tableName,"stunum=?",new String[]{"004"});
            Toast.makeText(this,R.string.Succstr,Toast.LENGTH_SHORT).show();
        }catch (Exception e){
            e.printStackTrace();
            Toast.makeText(this,R.string.Failstr,Toast.LENGTH_SHORT).show();
        }
        finally {
            db.close();
        }
    }

//數據庫的修改操作
    public void UpdataClick(View view){
        db = myDBHelper.getWritableDatabase();
        try {
            //方法一:拼接字符串
//            String sqlstr = "update "+databasepublicstr.tableName+" set stuname='馬超' where stunum = '004'";
//            db.execSQL(sqlstr);
            //方法2:數組形式
//            String sqlstr = "update "+databasepublicstr.tableName+
//                    " set stuname='?' where stunum = '?'";
//            String [] strings={"趙雲","004"};
//            db.execSQL(sqlstr,strings);
            //方法3:內置修改
            contentValues = new ContentValues();
            contentValues.put("stuname","馬超");
            contentValues.put("stunum","002");
            int i = db.update(databasepublicstr.tableName,contentValues,"stunum=?",new String[]{"002"});
            if(i>0){
                Toast.makeText(this,R.string.Succstr,Toast.LENGTH_SHORT).show();
            }else{
                Toast.makeText(this,"這條記錄不存在",Toast.LENGTH_SHORT).show();
            }

        }catch (Exception e){
            e.printStackTrace();
            Toast.makeText(this,R.string.Failstr,Toast.LENGTH_SHORT).show();
        }
        finally {
            db.close();
        }
    }

    TextView textView = null;
    public void QueryClick(View view){
        textView = findViewById(R.id.tv_query);
        db = myDBHelper.getWritableDatabase();
        try {
            //方法1:採用Sql字符串
//            String SqlStr="select * from stutable where stunum='?'";
//            String [] strings = {"001"};
//            Cursor cursor = db.rawQuery(SqlStr,strings);
            String SqlStr="select * from stutable";
            Cursor cursor = db.rawQuery(SqlStr,null);
            String Constr = "";
            while(cursor.moveToNext()){
                Constr+="學號:"+cursor.getString(1)+"姓名:"+cursor.getString(2)+"年齡:"+cursor.getString(3)+":\n";
            }
            textView.setText(Constr);
        }catch (Exception e){
            e.printStackTrace();
        }
        finally {
            db.close();
        }
    }
}

MyDBHelper.java(數據庫的初始化和升級)

package com.example.class0422;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import androidx.annotation.Nullable;

public class MyDBHelper extends SQLiteOpenHelper {
    public MyDBHelper(@Nullable Context context) {
        super(context, databasepublicstr.DataBaseName, null, databasepublicstr.DB_Version);
    }

//數據庫初始化執行的函數
    @Override
    public void onCreate(SQLiteDatabase db) {
        String SqlStr = "create table " + databasepublicstr.tableName+
                " (stuid integer PRIMARY KEY autoincrement,stunum varchar(10) unique,stuname varchar(20),stuage integer)";
        db.execSQL(SqlStr);
    }

//數據庫更新執行的函數
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//        String SqlStr1 = "create table " + databasepublicstr.tableTeacher+
//                " (teacherid integer PRIMARY KEY autoincrement,stunum varchar(10) unique,stuname varchar(20),stuage integer)";
//        db.execSQL(SqlStr1);
        String SqlStr2 = "create table " + databasepublicstr.tableFamily+
                " (familyid integer PRIMARY KEY autoincrement,familynum varchar(10) unique,familyname varchar(20),familyage integer)";
        db.execSQL(SqlStr2);
    }
}

databasepublicstr.java(保存數據庫和表的相關屬性)

package com.example.class0422;

public class databasepublicstr {

    public static String DataBaseName = "wl2database.db";
    public static int DB_Version = 1;
    public static int New_Version = 2;
    public static String tableName = "StuTable";
    public static String tableTeacher = "Teacher";
    public static String tableFamily = "Family";
}

1.創建數據庫時,如果手機存儲器中已經存在同名數據庫(即使表內容不相同),將不再創建。
2.升級數據庫時候,要注意數據庫更改數據庫的版本。
3.通過字符串拼接來操作數據庫時,要注意關鍵字和內容之間的空格不能丟。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章