Android之SQLite实现简单的增删改查

SQLite是一款轻型的数据库,是遵守ACID的关联式数据库管理系统,它的设计目标是嵌入式的,而且目前已经在很多嵌入式产品中使用了它,它占用资源非常的低,在嵌入式设备中,可能只需要几百K的内存就够了。它能够支持 Windows/Linux/Unix等等主流的操作系统,同时能够跟很多程序语言相结合,比如Tcl、PHP、Java、C++、.Net等,还有ODBC接口,同样比起 Mysql、PostgreSQL这两款开源世界著名的数据库管理系统来讲,它的处理速度比他们都快。
现在我们就用android studio来实现SQLite来实现简单的增删改查吧
布局界面



    
    
    
        
            
            
            
            
        
    
    
        

因为查询需要显示出来,所以我们再布局的最后定义一个ListView来显示查询的结果
要注意的是SQLite对于6.0以下的手机版本需要获取动态权限
我在Androidmainfest里声明了这三个权限
然后在MainActivity里申请了动态权限


    
    

MainActivity.java

package com.example.sqlitepro;

import android.Manifest;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.SimpleAdapter;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;

import java.io.File;
import java.io.IOException;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private Button button1,button2,button3,button4;
    private EditText editText1,editText2,editText3;
    private ListView listView;
    private RadioGroup group;
    //定义成全局的db
    private  SQLiteDatabase db;
    private String genderStr;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate (savedInstanceState);
        setContentView (R.layout.activity_main);
        //获取动态权限
        int permission = ContextCompat.checkSelfPermission (this,Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if(permission != PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions (this,new String[]{Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS,
            Manifest.permission.WRITE_EXTERNAL_STORAGE},1);
        }
        initView();
        button1.setOnClickListener (this);
        button2.setOnClickListener (this);
        button3.setOnClickListener (this);
        button4.setOnClickListener (this);
        //获取到RadioButton的值
        group.setOnCheckedChangeListener (new RadioGroup.OnCheckedChangeListener () {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if(checkedId == R.id.rb_man){
                    genderStr = "男";
                }else {
                    genderStr = "女";
                }
            }
        });
        String path = Environment.getExternalStorageDirectory () + "/stu2_tb";
        final SQLiteOpenHelper sqLiteOpenHelper = new SQLiteOpenHelper (this,path,null,1) {
            @Override
            public void onCreate(SQLiteDatabase db) {
                //如果没有找到相对应的数据库则创建一个新的数据库
                //如果手机里已经有这个数据库了,那么将不会再创建
                Toast.makeText (MainActivity.this,"创建数据库",Toast.LENGTH_SHORT).show ();
                String sql0 = "create table stu2_tb(_id integer primary key autoincrement,"+
                        "name varchar(20),"+
                        "age integer,"+
                        "gender varchar(10))";
                db.execSQL (sql0);
            }
            @Override
            public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
                //版本号大于之前的执行此更新操作
                Toast.makeText (MainActivity.this,"升级数据库",Toast.LENGTH_SHORT).show ();
            }
        };
        db = sqLiteOpenHelper.getReadableDatabase ();

    }
  //初始化控件
    private void initView() {
        button1 = findViewById (R.id.insert_btn);
        button2 = findViewById (R.id.select_btn);
        button3 = findViewById (R.id.update_btn);
        button4 = findViewById (R.id.delete_btn);
        editText1 = findViewById (R.id.et_name);
        editText2 = findViewById (R.id.et_age);
        editText3 = findViewById (R.id.et_id);
        listView = findViewById (R.id.listview);
        group = findViewById (R.id.radio_gp);
    }

    @Override
    public void onClick(View v) {
        //获取数据库对象
        String nameStr = editText1.getText ().toString ();
        String ageStr = editText2.getText ().toString ();
        String idStr = editText3.getText ().toString ();
        switch (v.getId ()){
            case R.id.insert_btn:
                //检查是否存在
//                File file = new File (path);
//                if(!file.exists ()){
//                    try {
//                        file.createNewFile ();
//                    } catch (IOException e) {
//                        e.printStackTrace ();
//                    }
//                }
                String sql = "insert into stu2_tb(name,age,gender) values('"+nameStr+"',"+ageStr+",'"+genderStr+"')";
                db.execSQL(sql);
                Toast.makeText (MainActivity.this,"添加成功",Toast.LENGTH_SHORT).show ();
                break;
            case R.id.select_btn:
                String sql2 = "select * from stu2_tb";
                //这个是实现查询具体的信息的代码
//                if(!idStr.equals ("")){
//                    sql2 +=" where _id    " + idStr;
//                }
                Cursor c = db.rawQuery (sql2,null);
                //这里因为显示的数据是一个ListView,所以需要创建一个适配器来进行数据的适配
                // SimpleCursorAdapter这个适配器的第二个参数是一个布局文件
                SimpleCursorAdapter adapter = new SimpleCursorAdapter (
                        this,R.layout.item,c,
                        new String[]{"_id","name","age","gender"},
                        new int[]{R.id.id_item,R.id.name_item,R.id.age_item,R.id.gender_item});
                listView.setAdapter (adapter);
                Toast.makeText (MainActivity.this,"查询成功",Toast.LENGTH_SHORT).show ();
                break;
            case R.id.update_btn:
                String sql4 = "update stu2_tb set name=?,age=?,gender=? where _id=?";
                db.execSQL (sql4,new String[]{nameStr,idStr,genderStr,ageStr});
                Toast.makeText (MainActivity.this,"修改成功",Toast.LENGTH_SHORT).show ();
                break;
            case  R.id.delete_btn:
                String sql3 = "delete from stu2_tb where _id =?";
                db.execSQL (sql3,new String[]{idStr});
                Toast.makeText (MainActivity.this,"删除成功",Toast.LENGTH_SHORT).show ();
                break;
        }
        editText1.setText ("");
        editText2.setText ("");
        editText3.setText ("");
    }
}

用来匹配适配器的布局文件
item.xml



    
    
    
    



实现的效果如图
Android之SQLite实现简单的增删改查_第1张图片
因为我之前做过测试,所以显示出来的数据的第一列的编号是从10开始的
这样就可以实现SQLite的增删改查啦
如果对于动态权限不是很了解的话可以参考一下下面的博客链接
https://blog.csdn.net/qq_42889476/article/details/89927574

你可能感兴趣的:(Android)