数据库的增删查改--Cursor结果集和execSQL和rawQuery方法的使用--SQLiteDatabase类的getWritableDatabase和getReadableDatabase方法

InstrumentationRegistry.getInstrumentation().getTargetContext();可以获取上下文对象
SQLiteDatabase db=dbOpenHelper.getWritableDatabase();
SQLiteDatabase db1=dbOpenHelper.getWritableDatabase();
db和db1是同一个对象的,因为dbOpenHelper是同一个对象,SQLiteOpenHelper.getWritableDatabase是有缓存数据库实例功能的

结果集游标对象Cursor,Cursor专门用来查询rawQuery返回的结果集,进行随机访问,可以移动指针指向到某一条记录。
Cursor提供的常用方法:
moveToNext()方法可以将游标从当前行移动到下一行,如果已经移过了结果集的最后一行,返回结果为false,否则为true。
moveToPrevious()方法(用于将游标从当前行移动到上一行,如果已经移过了结果集的第一行,返回值为false,否则为true )。
moveToFirst()方法(用于将游标移动到结果集的第一行,如果结果集为空,返回值为false,否则为true )
moveToLast()方法(用于将游标移动到结果集的最后一行,如果结果集为空,返回值为false,否则为true ) 。

SQL语句加双引号可以条用Java属性或对象
实际开发输入中用户可以会输入特殊符号之类,比如“&”的那么此SQL语句就会报错,所以需要转义,这里需要用到问号占位符(?)进行转义。execSQL和rawQuery方法第二个参数为SQL语句中占位符参数的值

SQLiteDatabase 提供的execSQL方法和rawQuery
execSQL:可以执行delete 、insert、update、和CREATE TABLE之类的更改行为的SQL语句
rawQuery:用来执行select的SQL语句
execSQL和execSQL方法的第一个参数为SQL语句,第二个参数为SQL语句中占位符参数的值

增加新纪录:


public class personService {
    //数据库对象
    private DBOpenHelper dbOpenHelper;
    private Context context;

	//传入上下文对象和数据库的操作
    public personService(Context context,DBOpenHelper dbOpenHelper) {
        this.context=context;
        this.dbOpenHelper=dbOpenHelper;
    }


    /*
    *  增
    *  */
    public void save(Person p){
        //获取数据库的操作
        SQLiteDatabase db=dbOpenHelper.getWritableDatabase();
       /* db和db1是同一个对象的,因为dbOpenHelper是同一个对象,SQLiteOpenHelper.getWritableDatabase是有缓存数据库实例功能的
        SQLiteDatabase db1=dbOpenHelper.getWritableDatabase();*/

        /*SQL语句加双引号可以条用Java属性或对象
        values的值是获取person对象里的数据
        此values值会出现语法问题,比如p.getName()获取的值中有引号或特殊符号之类的那么此SQL语句就会报错,,所以需要转义
        db.execSQL("insert into person(name,phone) values("+p.getName()+",'"+p.getPhone()+"')");*/

        //改进后,用问号(?)进行转义
        db.execSQL("insert into person(personid,name,phone) values(?,?,?)",
                //对问号负责
                //需要转义的数据
                new Object[]{p.getId(),p.getName(),p.getPhone()});
        Toast.makeText(context, "成功", Toast.LENGTH_SHORT).show();
        //当数据库只有在一个地方使用的时候可以不关闭,不关闭可以提高性能,因为不用频繁打开数据库
        //db.close();
        /*ContentValues values=new ContentValues();
        db.insert("name",null,values);*/
    }

查询记录:

SQLiteDatabase 提供的rawQuery方法
rawQuery:用来执行select的SQL语句

/*
    * 查询记录
    *
    * */
    public Person find(Integer id){

        //获取数据库的操作
        SQLiteDatabase db=dbOpenHelper.getReadableDatabase();

        /*
        getWritableDatabase当数据库的磁盘空间满了会报错

        getReadableDatabase内部会调用getWritableDatabase
        getWritableDatabase当数据库的磁盘空间满了getReadableDatabase会以只读的方式打开数据库
        在数据库磁盘空间没有满的情况下getReadableDatabase调用的是getWritableDatabase返回的实例

        */
        //在读取数据库的数据情况下一般用getReadableDatabase,因为如果数据库磁盘满了getWritableDatabase就读取不到数据了
        //getReadableDatabase在数据库磁盘没有满的情况下是可以添加数据的
        //得到一个结果集游标对象Cursor,Cursor专门用来查询rawQuery返回的结果集,进行随机访问,可以移动指针指向到某一条记录
        Cursor cursor=db.rawQuery("select * from person where personid=?", new String[]{id.toString()});

        //moveToFirst如果没有数据指针则移动不成功返回false。移动成功返回ture,证明有数据
        if(cursor.moveToFirst()){
            int personid=cursor.getInt(0);
            String personName=cursor.getString(1);
            String personPhone=cursor.getString(2);
            //添加进对象返回
            return new Person(personid,personName,personPhone);
        }
        Toast.makeText(context, "成功", Toast.LENGTH_SHORT).show();
        cursor.close();
        return null;
    }

删除记录:
SQLiteDatabase 提供的execSQL方法和rawQuery
execSQL:可以执行delete 、insert、update、和CREATE TABLE之类的更改行为的SQL语句


    /*
     * 删
     * @person id  记录id
     * */
    public void delete(Integer id){
        SQLiteDatabase db=dbOpenHelper.getWritableDatabase();
        //用ID查询然后删除
        db.execSQL("delete from person where personid=?",new Object[]{id});
        Toast.makeText(context, "删除成功", Toast.LENGTH_SHORT).show();
    }

更新记录:

 /*
     * 更新记录
     * @person p
     * */
    public void update(Person p){
        dbOpenHelper.getWritableDatabase().execSQL("update person set name=?,phone=? where personid=?",
                new Object[]{p.getName(),p.getPhone(),p.getId()});
        Toast.makeText(context, "更新成功", Toast.LENGTH_SHORT).show();
    }

调用以上的增删查改方法:
SQLiteDatabase
getWritableDatabase当数据库的磁盘空间满了会报错
getReadableDatabase内部会调用getWritableDatabase
当数据库的磁盘空间满了getReadableDatabase会以只读的方式打开数据库
在数据库磁盘空间没有满的情况下getReadableDatabase调用的是getWritableDatabase返回的实例
在读取数据库的数据情况下一般用getReadableDatabase,因为如果数据库磁盘满了getWritableDatabase就读取不到数据了
getReadableDatabase在数据库磁盘没有满的情况下是可以添加数据的


public class MainActivity extends AppCompatActivity {
    private EditText userid;
    private EditText name;
    private EditText phone;
    private TextView tv;
    private DBOpenHelper dbOpenHelper;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv=this.findViewById(R.id.cha);
        //获取id
        userid=findViewById(R.id.user);
        //添加
        this.findViewById(R.id.tianjia).setOnClickListener(new onClickTian());
        //查询
        this.findViewById(R.id.chaxun).setOnClickListener(new onClickCha());
        //删除
        this.findViewById(R.id.delete).setOnClickListener(new onDelete());
        //更新
        this.findViewById(R.id.Update).setOnClickListener(new onUpdate());
        //获取总数
        this.findViewById(R.id.count).setOnClickListener(new onCount());
        //分页查询
        this.findViewById(R.id.fenye).setOnClickListener(new onScrollDate());
        //获取姓名电话
        name=this.findViewById(R.id.name);
        phone=this.findViewById(R.id.phone);
        //创建数据库操作对象
        dbOpenHelper=new DBOpenHelper(this);
    }


    public void test(View view) {
//        dbOpenHelper=new DBOpenHelper(this);
        dbOpenHelper.getReadableDatabase();
    }

    //添加新纪录
    public class onClickTian implements View.OnClickListener{

        @Override
        public void onClick(View view) {
            //获取id
            String ids=userid.getText().toString();
            //获取姓名
            String names=name.getText().toString();
            //获取电话
            String phones=phone.getText().toString();
            personService ps=new personService(getBaseContext(),dbOpenHelper);
            if(!ids.isEmpty()&&!names.isEmpty()&&!phones.isEmpty()) {
                Person p=new Person(Integer.parseInt(ids),names,phones);
                ps.save(p);
            }else{Toast.makeText(getBaseContext(), "获取失败,请在上方输入要查询的id", Toast.LENGTH_SHORT).show();}
        }
    }

    //查询
    public class onClickCha implements View.OnClickListener{
        @Override
        public void onClick(View view) {
            personService ps=new personService(getBaseContext(),dbOpenHelper);
            String str=userid.getText().toString();
            if(!str.isEmpty()){
                    Person p=ps.find(Integer.parseInt(str));
                    tv.setText("查询到内容:"+"id:"+p.getId()+"--名字:"+p.getName()+"--电话:"+p.getPhone());
                    Toast.makeText(getBaseContext(),"id:"+p.getId()+"--名字:"+p.getName()+"--电话:"+p.getPhone() , Toast.LENGTH_SHORT).show();

            }else{Toast.makeText(getBaseContext(), "获取失败,请在上方输入要查询的id", Toast.LENGTH_SHORT).show();}

        }
    }


    //删除
    public class onDelete implements View.OnClickListener{

        @Override
        public void onClick(View view) {
            String str=userid.getText().toString();
            personService ps=new personService(getBaseContext(),dbOpenHelper);
            if(!str.isEmpty()) {
                ps.delete(Integer.parseInt(str));
            }else{Toast.makeText(getBaseContext(), "获取失败,请在上方输入要查询的id", Toast.LENGTH_SHORT).show();}

        }
    }

    //更新
    public class onUpdate implements View.OnClickListener{

        @Override
        public void onClick(View view) {
            //获取id
            String ids=userid.getText().toString();
            //获取姓名
            String names=name.getText().toString();
            //获取电话
            String phones=phone.getText().toString();
            personService ps=new personService(getBaseContext(),dbOpenHelper);
            if(!ids.isEmpty()&&!names.isEmpty()&&!phones.isEmpty()){
                //保存进对象
                Person p=new Person(Integer.parseInt(ids),names,phones);
                ps.update(p);
            }else{Toast.makeText(getBaseContext(), "获取失败,请在上方输入要查询的id", Toast.LENGTH_SHORT).show();}
        }
    }

    public class onScrollDate implements View.OnClickListener{
        @Override
        public void onClick(View view) {
            personService ps=new personService(getApplicationContext(),dbOpenHelper);
            List<Person> arr=  ps.getScrolld(0,10);
            for(Person p:arr){
                tv.setText("id:"+p.getId()+"--名字:"+p.getName()+"--电话:"+p.getPhone() );
            }
        }
    }

    public class onCount implements View.OnClickListener{
        @Override
        public void onClick(View view) {
            personService ps=new personService(getBaseContext(),dbOpenHelper);
            tv.setText("总数:"+ps.getCount());
        }
    }
}

创建数据库:

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

import androidx.annotation.Nullable;

public class DBOpenHelper extends SQLiteOpenHelper {
    private Context context;
    public DBOpenHelper(@Nullable Context context) {
        /*context上下文对象
        * name数据库名称
        * factory 游标工厂 (一般为null)  null表示使用系统默认的游标工厂
        * version版本号
        * */
        super(context, "name", null, 2);
        this.context=context;
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {//是在数据库每次被创建的时候调用
        sqLiteDatabase.execSQL("create table person(personid Integer primary key autoincrement,name varchar(20),phone varchar(20))");
        Toast.makeText(context, "成功", Toast.LENGTH_SHORT).show();
    }

    @Override//是在每次数据库的版本变更时候调用
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
        sqLiteDatabase.execSQL("ALTER TABLE person ADD phone varchar(20)");
    }
}

保存用户id、用户名和电话的对象类:

package com.example.domain;


public class Person {
    private Integer id;
    private String name;
    private String phone;

    public Person(String name, String phone) {
        this.name = name;
        this.phone = phone;
    }

    public Person(int personid) {
        super();
    }

    public Person(Integer id, String name, String phone) {
        this.id=id;
        this.name=name;
        this.phone=phone;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }
}

安卓界面xml文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:layout_height="match_parent" android:layout_width="match_parent" android:orientation="vertical"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <EditText
        android:id="@+id/user"
        android:hint="账号:"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

    <EditText
        android:id="@+id/name"
        android:hint="名字:"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

    <EditText
        android:id="@+id/phone"
        android:hint="电话:"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

    <Button
        android:text="点击"
        android:onClick="test"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

    <Button
        android:text="添加数据"
        android:id="@+id/tianjia"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

    <Button
        android:text="查询"
        android:id="@+id/chaxun"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

    <Button
        android:text="删除"
        android:id="@+id/delete"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
    <Button
        android:text="更新"
        android:id="@+id/Update"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

    <Button
        android:text="分页查询"
        android:id="@+id/fenye"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

    <Button
        android:text="获取总数"
        android:id="@+id/count"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

    <TextView
        android:id="@+id/cha"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

</LinearLayout>

界面:
请添加图片描述

  • 3
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

TL。

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值