Android Studio4.0中SQLite的操作使用

**

Android Studio4.0中SQLite的操作使用

**
数据的存储是需要借助数据库来完成的,在Android中系统内置了数据库——SQLite数据库,SQLite是一款轻量级的关系型数据库,它的运算速度非常快,占用的资源很少。下面我通过一个小demo展示一下数据库SQLite是如何进行操作的。
先展示一下demo的效果:
在这里插入图片描述这就是最终demo的效果,建立的数据库里是一个包含编号、姓名、年龄的存储表。
布局文件activity_main.xml代码如下:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">


    <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="编  号"
        android:textSize="30dp"
        android:textColor="@android:color/holo_red_light"

        />

    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:ems="10"
        android:inputType="textPersonName"
        android:text=""
        android:textColor="@android:color/holo_blue_bright"/>
</LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/textView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="姓  名"
            android:textSize="30dp"
            android:textColor="@android:color/holo_red_light"

            />

        <EditText
            android:id="@+id/editText2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:ems="10"
            android:inputType="textPersonName"
            android:text=""
            android:textColor="@android:color/holo_blue_bright"/>
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/textView3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="年  龄"
            android:textSize="30dp"
            android:textColor="@android:color/holo_red_light"

            />

        <EditText
            android:id="@+id/editText3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:ems="10"
            android:inputType="textPersonName"
            android:text=""
            android:textColor="@android:color/holo_blue_bright"/>
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/textView4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="查找的编号"
            android:textSize="30dp"
            android:textColor="@android:color/holo_red_light"

            />

        <EditText
            android:id="@+id/editText4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:ems="10"
            android:inputType="textPersonName"
            android:text=""
            android:textColor="@android:color/holo_blue_bright"/>
        <Button
            android:id="@+id/button_searchid"
            android:onClick="search_id"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/button"
            android:textSize="30dp"
            android:textColor="@android:color/white"
            android:text="查 找"/>

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_marginTop="20dp">

        <TextView
            android:id="@+id/textView5"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="查找的姓名"
            android:textSize="30dp"
            android:textColor="@android:color/holo_red_light"

            />

        <EditText
            android:id="@+id/editText5"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:ems="10"
            android:inputType="textPersonName"
            android:text=""
            android:textColor="@android:color/holo_blue_bright"/>
        <Button
            android:id="@+id/button_searchname"
            android:onClick="search_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/button"
            android:textSize="30dp"
            android:textColor="@android:color/white"
            android:text="查 找"/>

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
       android:orientation="horizontal"
        android:layout_marginTop="30dp"
        android:gravity="center">
    <Button
        android:id="@+id/button_add"
        android:onClick="add"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/button"
        android:textSize="30dp"
        android:textColor="@android:color/white"
        android:text="添  加"/>

    <Button
        android:id="@+id/button_delete"
        android:onClick="delete"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/button"
        android:textSize="30dp"
        android:textColor="@android:color/white"
        android:text="删  除" 
        android:layout_marginLeft="30dp"/>
        
    <Button
    android:id="@+id/button_adjust"
    android:onClick="upgrade"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/button"
    android:textSize="30dp"
    android:textColor="@android:color/white"
    android:text="修  改" 
        android:layout_marginLeft="30dp"/>
</LinearLayout>
    
    <TextView
        android:id="@+id/textView6"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="结 果:"
        android:textSize="40dp"
        android:textStyle="bold"
        android:layout_marginTop="30dp"/>

</LinearLayout>

其中 button.xml代码如下所示:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="false" android:drawable="@drawable/button_false"></item>
    <item android:state_pressed="true" android:drawable="@drawable/button_true"></item>
</selector>

button_false.xml代码如下:

<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="@android:color/darker_gray"></solid>
</shape>

button_true.xml代码如下:

<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="@color/colorPrimary"></solid>
<corners android:radius="30dp"></corners>
</shape>

上面设置button在按和没按下的两种状态,目的是为了凸显出按钮按下的效果。
下面介绍具体的实践部分:
首先新建一个Mydatabase的类,用来继承管理数据库的帮助类SQLiteOpenHelper。
Mydatabase.java如下代码:

package com.example.sql;

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

import androidx.annotation.Nullable;

public class Mydatabase extends SQLiteOpenHelper {
     static String name="bookstore.db";
     static int version=2;


    public Mydatabase(@Nullable Context context) {
        super(context, name, null, version);
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {

        String create_user="create table user(编号 Integer,姓名 text,年龄 integer)";
        sqLiteDatabase.execSQL(create_user);
        String create_Book="create table book(编码 Integer,书名 text,价格 real)";
        sqLiteDatabase.execSQL(create_Book);

    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
        sqLiteDatabase.execSQL("drop table if exists user");
        sqLiteDatabase.execSQL("drop table if exists book");
        onCreate(sqLiteDatabase);

    }
}

在MainActivity中再具体实施添加数据、删除数据、查询数据等操作,代码如下所示:

package com.example.sql;

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.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private EditText bianhao;
    private EditText name;
    private EditText age;
    private EditText search_id;
    private EditText search_name;
    private TextView result;
    private Mydatabase mydatabase;
    private SQLiteDatabase database;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        bianhao = findViewById(R.id.editText1);
        name = findViewById(R.id.editText2);
        age = findViewById(R.id.editText3);
        search_id = findViewById(R.id.editText4);
        search_name = findViewById(R.id.editText5);
        result = findViewById(R.id.textView6);

        mydatabase = new Mydatabase(MainActivity.this);
        database = mydatabase.getWritableDatabase();

    }
//添加数据
    public void add(View view) {
        //第一种插入数据的方法
      // String sql="insert into user(编号,姓名,年龄)values(?,?,?)";
       //parseInt:用于解析字符,并返回整数
       // database.execSQL(sql,new Object[]{Integer.parseInt(bianhao.getText().toString()),name.getText(),Integer.parseInt(age.getText().toString())});
//第二种方法(编号不同)

        String search ="select * from user where 编号=?";
        Cursor cursor = database.rawQuery(search, new String[]{bianhao.getText().toString()});
        if(cursor.getCount()==0)
        {//开始组装数据
            ContentValues values=new ContentValues();
            values.put("编号",Integer.parseInt(bianhao.getText().toString()));
            values.put("姓名",name.getText().toString());
            values.put("年龄",Integer.parseInt(age.getText().toString()));
            database.insert("user",null,values);

        }else {
            Toast.makeText(getApplicationContext(),"您输入的编号已存在,请重新输入编号",Toast.LENGTH_SHORT).show();
        }
    }

//删除数据
    public void delete(View view) {
        String delete="delete from user where 编号=?";
        database.execSQL(delete,new Object[]{Integer.parseInt(bianhao.getText().toString())});

    }
    //更新数据
    public void upgrade(View view) {
        String upgrade="update user set 姓名=?,年龄=? where 编号=?";
        database.execSQL(upgrade,new Object[]{name.getText().toString(),Integer.parseInt(age.getText().toString()),Integer.parseInt(bianhao.getText().toString())});
    }

    //查找编号
    public void search_id(View view) {
        result.setText("");

      String sql="select * from user where 编号=?";
        Cursor cursor = database.rawQuery(sql, new String[]{search_id.getText().toString()});
        while (cursor.moveToNext()){
            String nn=cursor.getString(cursor.getColumnIndex("姓名"));
            int id=cursor.getInt(cursor.getColumnIndex("编号"));
          int xx=cursor.getInt(cursor.getColumnIndex("年龄"));

          result.append("\n编号:"+ id +"\t姓名:"+ nn +"\t年龄:"+ xx);



        }


    }
    //查找姓名
    public void search_name(View view) {

        result.setText("");

        String sql = "select * from user where 姓名=?";
        Cursor cursor = database.rawQuery(sql, new String[]{search_name.getText().toString()});
        while (cursor.moveToNext()) {
            String nn = cursor.getString(cursor.getColumnIndex("姓名"));
            int id = cursor.getInt(cursor.getColumnIndex("编号"));
            int xx = cursor.getInt(cursor.getColumnIndex("年龄"));

            result.append("\n编号:" + id + "\t姓名:" + nn + "\t年龄:" + xx);

        }


    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值