Android Studio SQLite 数据库 增删改查 简单

源码

效果展示

在这里插入图片描述
    所有操作都在这个界面完成,操作完直接显示

设计

    一个class用来创建数据库,建表,一个activity用来执行增删改查操作
在这里插入图片描述
在这里插入图片描述

代码

DatebaseHlper
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DatabaseHelper extends SQLiteOpenHelper {

    public DatabaseHelper(Context context){super(context,"Test.db",null,1);}
    //第一个参数是上下文,第二个参数是数据库名称,
    //第三个参数是CursorFactory对象,一般设置为null,第四个参数是数据库的版本
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE information(_id INTEGER PRIMARY KEY AUTOINCREMENT,name VARCHAR(20),age INTEGER)");
    }
	//创建表 表名information 表结构 自增id,字符串姓名,int年龄

    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        Log.d("myDeBug","数据库版本已更新");
    }
    //数据库版本发生变化时调用
}
DictActivity
布局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    >
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="姓名"
            android:textSize="30sp"
            />
        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="请输入姓名"
            android:textSize="20sp"
            android:id="@+id/name"
            />
    </LinearLayout>
    <LinearLayout

        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="年龄"
            android:textSize="30sp"
            />
        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="请输入年龄"
            android:textSize="20sp"
            android:id="@+id/age"
            />
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        >

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:textSize="20sp"
        android:text="插入"
        android:id="@+id/btn_insert"
        android:textAllCaps="false"
        />
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:textSize="20sp"
        android:text="更新"
        android:id="@+id/btn_update"
        android:textAllCaps="false"
        />
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
    android:textSize="20sp"
    android:text="查询"
    android:id="@+id/btn_search"
        android:textAllCaps="false"
    />
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
    android:textSize="20sp"
    android:text="删除"
    android:id="@+id/btn_delete"
        android:textAllCaps="false"
    />


</LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        >
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:id="@+id/tv_show"
            android:textSize="20sp"
            android:gravity="center_horizontal"/>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:id="@+id/tv_showAge"
            android:textSize="20sp"
            android:gravity="center_horizontal"
            />
</LinearLayout>


</LinearLayout>

    最外层垂直线性布局,内部三个线性布局,后两个用的水平排版。
    因为不清楚表格TextView怎么做,TableView太麻烦,索性两个TextView,weight都设置为1就可以了。

主要代码
import androidx.appcompat.app.AppCompatActivity;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

public class DictActivity extends AppCompatActivity {
    private Button insertButton,updateButton,searchButton,deleteButton;
    private EditText name,age;
    private TextView show,showAge;
    final DatabaseHelper dbHelper=new DatabaseHelper(DictActivity.this);
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dict);

        insertButton=findViewById(R.id.btn_insert);
        updateButton=findViewById(R.id.btn_update);
        searchButton=findViewById(R.id.btn_search);
        deleteButton=findViewById(R.id.btn_delete);
        name=findViewById(R.id.name);
        age=findViewById(R.id.age);
        show=findViewById(R.id.tv_show);
        showAge=findViewById(R.id.tv_showAge);



        SQLiteDatabase db=dbHelper.getReadableDatabase();

        myShow();
        

        insertButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                SQLiteDatabase db=dbHelper.getWritableDatabase();
                ContentValues values=new ContentValues();
                values.put("name",name.getText().toString());
                values.put("age",age.getText().toString());
                long id =db.insert("information",null,values);
                Log.d("myDeBug","insert");

                myShow();
                

                db.close();
                name.setText(null);
                age.setText(null);
            }
        });
        updateButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                SQLiteDatabase db=dbHelper.getWritableDatabase();
                ContentValues values=new ContentValues();
                values.put("age",age.getText().toString());
                db.update("information",values,"name=?",new String[]{name.getText().toString()});
                
                    myShow();


                db.close();
                Log.d("myDebug","update");
                name.setText(null);
                age.setText(null);
            }
        });
        searchButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                SQLiteDatabase db=dbHelper.getWritableDatabase();
                String name1=name.getText().toString();
                show.setText(null);
                if(name1.equals("")){
//                    show.setText("姓名");
//                    showAge.setText("年龄");
//                    Cursor cursor = db.rawQuery("select * from information",null);
//
//                    while (cursor.moveToNext()) {
//                        String newName = cursor.getString(cursor.getColumnIndex("name"));
//                        int newAge = cursor.getInt(cursor.getColumnIndex("age"));
//                        show.setText(show.getText() + "\n" + newName);
//                        showAge.setText(showAge.getText()+"\n" + newAge);
//                    }

                    myShow();
                    
                    db.close();
                }else {
                    show.setText("姓名");
                    showAge.setText("年龄");
                    Cursor cursor = db.rawQuery("select * from information where name = ? ", new String[]{name1});

                    while (cursor.moveToNext()) {
                        String newName = cursor.getString(cursor.getColumnIndex("name"));
                        int newAge = cursor.getInt(cursor.getColumnIndex("age"));
//                        show.setText(show.getText() + "\n" + newName + "\t" + newAge);
                        show.setText(show.getText() + "\n" + newName);
                        showAge.setText(showAge.getText()+"\n" + newAge);
                    }

                    cursor.close();
                    db.close();
                    name.setText(null);
                    age.setText(null);
                }
            }
        });
        deleteButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                SQLiteDatabase db=dbHelper.getWritableDatabase();
                db.delete("information","name=?",new String[]{name.getText().toString()});

                
                myShow();
             
                
                db.close();
                Log.d("myDeBug","DeleteSuccess");
                name.setText(null);
                age.setText(null);
            }
        });

    }

    public void myShow(){
        SQLiteDatabase db=dbHelper.getReadableDatabase();


        show.setText("姓名");
        showAge.setText("年龄");
        Cursor cursor = db.rawQuery("select * from information",null);

        while (cursor.moveToNext()) {
            String newName = cursor.getString(cursor.getColumnIndex("name"));
            int newAge = cursor.getInt(cursor.getColumnIndex("age"));
            show.setText(show.getText() + "\n" + newName);
            showAge.setText(showAge.getText()+"\n" + newAge);
        }
        cursor.close();
    }

    实例化四个Button,两个EditText,两个TextView,连接数据库
按钮增加监听点击事件,editText用来获取输入,TextView来展示成果。
    说一下myShow()方法,在这个里面我写了展示代码,先连接数据库,设置“表头”,用cursor来遍历表内所有信息,直到没有行,每过一行,获取name和age列的数据,设置TextView的文本(setText())之前的文本,换行,加上这行的数据。其他的增删改查,只是简单地执行sql语句或者调用SQLiteDatabase的方法。
在这里解释一下cursor
    Cursor默认是行的集合:
    查询出来的cursor的初始位置是指向第一条记录的前一个位置的
    cursor.moveToFirst()指向查询结果的第一个位置。
    一般通过判断cursor.moveToFirst()的值为true或false来确定查询结果是否为空。cursor.moveToNext()是用来做循环的,一般这样来用:while(cursor.moveToNext()){ }
    cursor.moveToPrevious()是指向当前记录的上一个记录,是和moveToNext相对应的;
    cursor.moveToLast()指向查询结果的最后一条记录
    使用cursor可以很方便的处理查询结果以便得到想要的数据
    上面关于cursor这部分来自Cursor.moveToNext();和Cursor.moveToFirst();

  • 50
    点赞
  • 386
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 23
    评论
### 回答1: Android Studio中使用SQLite数据库进行增删改查的步骤如下: 1. 创建数据库Android Studio中,可以使用SQLiteOpenHelper类来创建和管理数据库。首先,需要创建一个继承自SQLiteOpenHelper的类,并实现onCreate()和onUpgrade()方法。在onCreate()方法中,可以创建数据库表和初始化数据。 2. 插入数据 使用ContentValues类来存储要插入的数据,然后使用insert()方法将数据插入到数据库中。 3. 查询数据 使用query()方法查询数据库中的数据,可以指定查询条件、排序方式等参数。查询结果会返回一个Cursor对象,可以通过Cursor对象遍历查询结果。 4. 更新数据 使用ContentValues类来存储要更新的数据,然后使用update()方法将数据更新到数据库中。 5. 删除数据 使用delete()方法删除数据库中的数据,可以指定删除条件。 以上就是Android Studio中使用SQLite数据库进行增删改查的基本步骤。 ### 回答2: SQLiteAndroid Studio中内置的轻量级关系型数据库。 它在应用程序中被广泛使用,可以轻松地进行数据位置的插入、更新、删除和查询。下面将对如何在Android Studio增删改查SQLite数据库进行详细介绍。 1. 创建数据库Android Studio中,打开新的“Android项目”并在后台中打开SQLite数据库。 首先需要在该项目的build.gradle文件中添加以下代码: ```java implementation 'com.android.support:support-sqlite:28.0.0' ``` 随后,我们建立一个新类,并在该类中创建由SQLiteOpenHelper扩展而来的helper类。 这可以通过从SQLiteOpenHelper创建一个适当的构造函数,并覆盖其onCreate()和onUpgrade()方法来完成。完成后,在主要应用程序中实例化helper。 2. 增加数据 要添加新数据,请创建一个行对象,然后可以使用该表的insert()方法将其插入到数据库中。下面是一个示例代码: ```java SQLiteDatabase db = this.getWritableDatabase(); ContentValues contentValues = new ContentValues(); contentValues.put("name", “John Smith”); contentValues.put("age", 23); db.insert(“mytable”, null, contentValues); ``` 其中mytable是表名,name和age是表中列名。 3. 更新数据 要更新数据,请使用Table的update()方法。要更新给定行中的具体数据,请使用ContentValues对象,该对象可以使用put()方法来指定一个新值。下面是一个示例代码: ```java SQLiteDatabase db = this.getWritableDatabase(); ContentValues contentValues = new ContentValues(); contentValues.put("age", 25); db.update(“tablename”, contentValues, “id=4”, null); ``` 这将会把id值为4的行的年龄值更新为25。 4. 删除数据 要删除数据,请使用Table的delete()方法。这个方法需要一个SQL语句作为参数。例如,如果要删除表中的一个特定行,请使用以下代码: ```java SQLiteDatabase db = this.getWritableDatabase(); db.delete(“mytable”, “id=2”, null); ``` 这将删除表mytable中id为2的行。 5. 查询数据 要查询数据,请使用query()方法。该方法需要传入一个表名、要返回的列和一些可选的where、group by和having语句的参数。下面是一个示例代码: ```java SQLiteDatabase db = this.getWritableDatabase(); Cursor cursor = db.query(“mytable”, new String[]{“id”, “name”, “age”}, null, null, null, null, null); ``` 这会查询mytable表中的id、name和age列,并将结果存储在Cursor对象cursor中。 以上是关于如何在Android Studio增删改查SQLite数据库的简要介绍,这个过程还可以通过使用ORM类库等其他方法来简化。 但是,以上方法是SQLite基础部分中较为重要的部分。如有不懂之处,可以查看Android Studio SQLite官方文档进行更全面的了解。 ### 回答3: 在 Android Studio 中,开发者可以使用 SQLite 数据库来存储和管理应用程序中的数据。SQLite 是一种轻量级的关系型数据库,它非常适合于移动应用程序的存储需求。在本文中,我们将介绍如何使用 Android Studio 来完成 SQLite 数据库增删改查操作。 首先,我们需要在 Android Studio 中创建一个新的 Android 项目。在项目创建的过程中,需要设置应用程序的名称、包名和所支持的最低 API 级别等信息。之后,我们需要创建一个新的数据库表,表中包含应用程序需要存储的数据。 我们可以使用 SQLiteOpenHelper 类来创建和管理数据库SQLiteOpenHelper 类提供了一些方法来帮助我们处理 SQLite 数据库的创建和更新。在创建一个 SQLiteOpenHelper 对象时,我们需要提供数据库名称、版本号和表的结构。 接下来,我们将介绍如何使用 SQLiteDatabase 类来完成增删改查操作。SQLiteDatabase 类提供了一些方法来帮助我们对数据库进行操作。 1. 增加数据 使用 insert() 方法可以向数据库表中插入一行数据。insert() 方法需要传入表名、要插入的数据和一个选项参数。以下是一个示例: SQLiteDatabase db = dbHelper.getWritableDatabase(); ContentValues values = new ContentValues(); values.put("name", "Tom"); values.put("age", 18); db.insert("students", null, values); 2. 删除数据 使用 delete() 方法可以从数据库表中删除一行或多行数据。delete() 方法需要传入表名和一个选择字符串来限制删除范围。以下是一个示例: SQLiteDatabase db = dbHelper.getWritableDatabase(); db.delete("students", "name=?", new String[]{"Tom"}); 3. 修改数据 使用 update() 方法可以修改数据库表中的一行或多行数据。update() 方法需要传入表名、要修改的数据和一个选择字符串来限制修改范围。以下是一个示例: SQLiteDatabase db = dbHelper.getWritableDatabase(); ContentValues values = new ContentValues(); values.put("age", 20); db.update("students", values, "name=?", new String[]{"Tom"}); 4. 查询数据 使用 query() 方法可以从数据库表中查询一行或多行数据。query() 方法需要传入表名、要查询的列、一个选择字符串和一个排序字符串。以下是一个示例: SQLiteDatabase db = dbHelper.getReadableDatabase(); Cursor cursor = db.query("students", new String[]{"name", "age"}, "age=?", new String[]{"20"}, null, null, null); if (cursor != null) { while (cursor.moveToNext()) { String name = cursor.getString(cursor.getColumnIndex("name")); int age = cursor.getInt(cursor.getColumnIndex("age")); Log.d(TAG, "name:" + name + ", age:" + age); } cursor.close(); } 在使用 SQLite 数据库过程中,我们需要注意一些事项。比如,我们需要保证数据库的打开和关闭操作是成对出现的,以避免资源的浪费;我们还需要注意表名、列名和选择字符串等信息的正确性,否则会导致数据操作失败。此外,还应该使用事务来保证数据库操作的正确性和一致性。 总之,使用 Android StudioSQLite 数据库功能可以帮助我们方便地管理应用程序中的数据。通过学习 SQLite 数据库增删改查操作,我们可以更好地开发出高质量、稳定性的移动应用程序。
评论 23
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

小明和大树

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

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

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

打赏作者

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

抵扣说明:

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

余额充值