android studio实验之SQLite

数据库存储是 Android 数据存储中非常重要的内容,Android 提供一个轻量级的嵌入式数据库 SQLite,本次试验将学习如何通过代码建立数据库,并实现添加、删除、查找和更新等基本操作。

建立一个数据库并完成增删查改操作。

android studio实验之SQLite_第1张图片

 

activity_main.xml





    
        
        

        
        
    
    
        
        

        
        
    
    
        

            

People.java

package com.example.sqliteexperiment;


public class People {
    public int ID = -1;
    public String Name;
    public String Sex;
    public String Department;
    public String Monney;

    @Override
    public String toString() {
        String result = "";
        result += "ID:" + this.ID + ",";
        result += "姓名" + this.Name + ",";
        result += "性别" + this.Sex + ",";
        result += "部门" + this.Department + ",";
        result += "工资" + this.Monney ;
        return result;
    }
}

DBADapter.java

package com.example.sqliteexperiment;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.Toast;

import androidx.annotation.Nullable;

public class DBAdapter {
    private static final String DB_NAME="People.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_SEX="sex";
    public static final String KEY_DEPARTMENT="department";
    public static final String KEY_MONNEY="monney";

    private SQLiteDatabase db;
    private final Context context;
    private DBOpenHelper dbOpenHelper;

    private static final String DB_CREATE="create table "+
            DB_TABLE+" ("+KEY_ID+" integer primary key autoincrement, "+
            KEY_NAME+" text not null, "+KEY_SEX+" text not null, "+KEY_DEPARTMENT+
            " text not null, "+KEY_MONNEY+" text not null);";

    public DBAdapter(Context _context){
        context=_context;
    //    Toast.makeText(context.getApplicationContext(),"nihao",Toast.LENGTH_SHORT).show();
    }

    public void close(){
        if(db!=null){
            db.close();
            db=null;
        }
    }

    public void open()throws SQLiteException{
        dbOpenHelper=new DBOpenHelper(context,DB_NAME,null,DB_VERSION);
        try{
            db=dbOpenHelper.getWritableDatabase();

        }catch(SQLiteException ex){
            db=dbOpenHelper.getReadableDatabase();
        }
    }

    private static class DBOpenHelper extends SQLiteOpenHelper{
        public DBOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory,int version){
            super(context,name,factory,version);
        }
        private static final String DB_CREATE="create table "+
                DB_TABLE+" ("+KEY_ID+" integer primary key autoincrement, "+
                KEY_NAME+" text not null, "+KEY_SEX+" text not null, "+KEY_DEPARTMENT+
                " text not null, "+KEY_MONNEY+" text not null);";
        @Override
        public void onCreate(SQLiteDatabase _db){
            _db.execSQL(DB_CREATE);
        }
        @Override
        public void onUpgrade(SQLiteDatabase _db,int _oldVersion,int _newVersion){
            _db.execSQL("DROP TABLE IF EXISTS "+DB_TABLE);
            onCreate(_db);
        }
    };

    /*
    public long insert(People people){}
    public long deleteAllData(){ }
    public long deleteOneData(long id){ }
    public People[] queryAllData(){ }
    public People[] queryOneData(){ }
    public long updateOneData(long id,People people){ }

    private People[] ConvertTopeople(Cursor cursor){ }
    */
    public long insert(People people){
        ContentValues newValues=new ContentValues();
        newValues.put(KEY_NAME,people.Name);
        newValues.put(KEY_SEX,people.Sex);
        newValues.put(KEY_DEPARTMENT,people.Department);
        newValues.put(KEY_MONNEY,people.Monney);

        return db.insert(DB_TABLE,null,newValues);
    }
    public People[] getOneData(long id){
        Cursor results=db.query(DB_TABLE,new String[]{KEY_ID,KEY_NAME,KEY_SEX,KEY_DEPARTMENT,KEY_MONNEY},KEY_ID+"="+id,null,null,null,null);
        return ConvertToPeople(results);
    }
    public People[] getAllData(){
        Cursor results=db.query(DB_TABLE,new String[]{KEY_ID,KEY_NAME,KEY_SEX,KEY_DEPARTMENT,KEY_MONNEY},null,null,null,null,null);
        return ConvertToPeople(results);
    }
    @SuppressLint("Range")
    private People[] ConvertToPeople(Cursor cursor){//返回数据库全部数据
        int resultCounts=cursor.getCount();
        cursor.moveToFirst();
        People[] peoples=new People[resultCounts];
        for(int i=0;i

MainActivity.java

package com.example.sqliteexperiment;

import androidx.appcompat.app.AppCompatActivity;

import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    EditText ED_name,ED_sex,ED_department,ED_monney,ED_id;
    Button BT_add,BT_show,BT_clear_show,BT_clearall,BT_id_clear,BT_select,BT_id_update;
    DBAdapter dbAdapter;
    SQLiteDatabase db;
    TextView lable;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        DBAdapter dbadapter=new DBAdapter(MainActivity.this);
        ED_name=findViewById(R.id.name);
        ED_sex=findViewById(R.id.sex);
        ED_department=findViewById(R.id.department);
        ED_monney=findViewById(R.id.monney);
        ED_id=findViewById(R.id.id);

        BT_add=findViewById(R.id.bt_add);
        BT_show=findViewById(R.id.bt_show);
        BT_clear_show=findViewById(R.id.bt_clear_show);
        BT_clearall=findViewById(R.id.bt_clearall);
        BT_id_clear=findViewById(R.id.bt_id_clear);
        BT_select=findViewById(R.id.bt_id_select);
        BT_id_update=findViewById(R.id.bt_id_update);
        lable=findViewById(R.id.lable);
        dbAdapter=new DBAdapter(this);
        dbAdapter.open();

        BT_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                People t=new People();
                t.Name=ED_name.getText().toString();
                t.Sex=ED_sex.getText().toString();
                t.Department=ED_department.getText().toString();
                t.Monney=ED_monney.getText().toString();

                long colunm=dbAdapter.insert(t);
                if(colunm==-1){
                    lable.setText("添加过程出错误");
                }else{
                    lable.setText("成功添加数据,ID:"+String.valueOf(colunm));
                }
            }
        });
        BT_show.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                People[] peoples=dbAdapter.getAllData();
                    if(peoples.length==0){
                        lable.setText("数据库中没有数据");
                    }
                    String t="数据库:\n";
                    for(int i =0;i0?"成功":"失败");
                lable.setText(msg);
            }
        });
        BT_select.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int id=Integer.parseInt(ED_id.getText().toString());
                People people[]=dbAdapter.getOneData(id);
                if(people==null){
                    lable.setText("ID为"+id+"的数据不存在");
                }else{
                    lable.setText("查询成功:\n"+people[0].toString());
                }
            }
        });
        BT_id_update.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String s=ED_id.getText().toString();
                if(s.equals("")){
                    lable.setText("未输入ID");
                    return;
                }
                int id=Integer.parseInt(ED_id.getText().toString());

                People t=new People();
                t.Name=ED_name.getText().toString();
                t.Sex=ED_sex.getText().toString();
                t.Department=ED_department.getText().toString();
                t.Monney=ED_monney.getText().toString();
                long n=dbAdapter.updateOneData(id,t);
                if(n<0){
                    lable.setText("更新过程错误");
                }else{
                    lable.setText("成功更新数据"+String.valueOf(n)+"条");
                }
            }
        });

    }
    @Override
    protected void onStop(){
        super.onStop();
        dbAdapter.close();
    }
}

你可能感兴趣的:(sqlite,android,studio,android)