Android数据库(SQLite)的简单使用——增、删、查改功能的简单实现

记录一下Android数据库的增删查改的简单使用

话不多说,先献上你们最爱的效果图~
这边我用的是一个ListView来展示数据库里的数据
在这里插入图片描述

准备工作:
先写一个类继承SQLiteOpenHelper,因为SQLiteOpenHelper.java是一个Android提供的抽象类,我们要使用就写一个类继承它~
OpenHelper.java
public class OpenHelper extends SQLiteOpenHelper {

    public OpenHelper(Context context) {
        super(context,"sq.db",null,1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        //拓展:主键标识  primary key autoincrement
        String sql="create table "+"tbname"+"(id text,name text,age text )";
        db.execSQL(sql);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }
}
然后在Activity中实例化一下OpenHelper和SQLiteDatabase
OpenHelper openHelper= new OpenHelper(SQActivity.this);
SQLiteDatabase db = openHelper.getWritableDatabase();

这样子可以说准备工作就做完了,可以开始功能的实现了。

功能实现:增

首先实例化一下ContentValues,然后用put的方式以key-value(键对值)的形式传入数据,最后SQLiteDatabase的insert方法插入数据库。

private void setSQ(String id, String name, String age) {    //增
        ContentValues cv=new ContentValues();
        cv.put("id", id);
        cv.put("name", name);
        cv.put("age", age);
        //分别插入id name age三个数据,然后调用insert方法进行插入
        db.insert("tbname", null, cv);
    }
功能实现:删

删除就一行代码~SQLiteDatabase的delete的方法实现,这里只演示根据id来删除对应的数据。

private void getDel(String str_del) {  //删
        //这里仅演示根据ID删除某条数据
        db.delete("tbname", "id=?", new String[]{str_del});
    }
功能实现:查

首先创建一个Cursor 游标,然后遍历所有数据,这里由于我是用的ListView来展示数据,所以在while循环里面直接把数据传入到List中,cursor.getString(0)这个就是获取你每条数据的第一个数据的意思,也就是我传入的id。

 private void getSQ() {    //查
        //创建游标 cursor 并用游标遍历所有数据
       Cursor cursor = db.query("tbname", null, null, null, null, null, null);
        while (cursor.moveToNext()) {
            bean = new SQBean(cursor.getString(0), cursor.getString(1), cursor.getString(2));
            list.add(bean);
        }
        cursor.close();//关闭游标(cursor)释放资源
    }
功能实现:改

更改数据库中的内容的话,你需要再实例化一个ContentValues,然后添加一个数据到里面,最后利用SQLiteDatabase的update方法实现新旧数据的更新。(我这里是对name来进行更新)

 private void getUpData() {//改
        ContentValues cv_Updata=new ContentValues();
        cv_Updata.put("name",editUpdatastr.getText().toString());
        db.update("tbname", cv_Updata, "name=?", new String[]{editUpdataid.getText().toString()});
    }

如果还有什么不懂的可以下方评论区留言讨论!

最后贴上完整的代码:(ListView的Adapter和Bean就不贴了)

SQActivity.java

public class SQActivity extends AppCompatActivity implements View.OnClickListener {

    private EditText e1;
    private EditText e2;
    private EditText e3;
    private Button btn;
    private ListView lv;
    private EditText editDel;
    private Button buttonDel;
    private EditText editUpdataid;
    private EditText editUpdatastr;
    private Button buttonUpdata;
    private Button buttonRead;

    private OpenHelper openHelper;
    private SQLiteDatabase db;

    private SQBean bean;
    private SQAdapter adapter;
    private List<SQBean> list = new ArrayList<>();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sq);
        initView();
        openHelper= new OpenHelper(SQActivity.this);
        db = openHelper.getWritableDatabase();

        adapter = new SQAdapter(SQActivity.this, list);
        lv.setAdapter(adapter);
    }

    private void setSQ(String id, String name, String age) {    //增
        ContentValues cv=new ContentValues();
        cv.put("id", id);
        cv.put("name", name);
        cv.put("age", age);
        //分别插入id name age三歌数据,然后调用insert方法进行插入
        db.insert("tbname", null, cv);
    }

    private void getDel(String str_del) {  //删
        //这里仅演示根据ID删除某条数据
        db.delete("tbname", "id=?", new String[]{str_del});
    }

    private void getSQ() {    //查
        //创建游标 cursor 并用游标遍历所有数据
       Cursor cursor = db.query("tbname", null, null, null, null, null, null);
        while (cursor.moveToNext()) {
            bean = new SQBean(cursor.getString(0), cursor.getString(1), cursor.getString(2));
            list.add(bean);
        }
        cursor.close();//关闭游标(cursor)释放资源
    }

    private void getUpData() {//改
        ContentValues cv_Updata=new ContentValues();
        cv_Updata.put("name",editUpdatastr.getText().toString());
        db.update("tbname", cv_Updata, "name=?", new String[]{editUpdataid.getText().toString()});
    }

    private void initView() {
        e1 = (EditText) findViewById(R.id.e1);
        e2 = (EditText) findViewById(R.id.e2);
        e3 = (EditText) findViewById(R.id.e3);
        btn = (Button) findViewById(R.id.btn);
        lv = (ListView) findViewById(R.id.lv);
        editDel = (EditText) findViewById(R.id.edit_del);
        buttonDel = (Button) findViewById(R.id.button_del);
        editUpdataid = (EditText) findViewById(R.id.edit_updataid);
        editUpdatastr = (EditText) findViewById(R.id.edit_updatastr);
        buttonUpdata = (Button) findViewById(R.id.button_updata);
        buttonRead = (Button) findViewById(R.id.button_read);
        btn.setOnClickListener(this);
        buttonUpdata.setOnClickListener(this);
        buttonRead.setOnClickListener(this);
        buttonDel.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn:                //增
                setSQ(e1.getText().toString(), e2.getText().toString(), e3.getText().toString());
                Toast.makeText(this, "插入数据成功", Toast.LENGTH_SHORT).show();
                break;
            case R.id.button_del:          //删
                getDel(editDel.getText().toString());
                Toast.makeText(this, "删除成功", Toast.LENGTH_SHORT).show();
                break;
            case R.id.button_read:        //查
                list.clear();//先清空旧数据防止重叠
                getSQ();
                adapter.notifyDataSetChanged();//更新List列表
                Toast.makeText(this, "查询成功", Toast.LENGTH_SHORT).show();
                break;
            case R.id.button_updata:     //改
                getUpData();
                Toast.makeText(this, "更改成功", Toast.LENGTH_SHORT).show();
                break;
        }
    }
}

activity_sq.xml

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


    <LinearLayout
        android:gravity="center"
        android:padding="10dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <EditText
            android:singleLine="true"
            android:maxLines="1"
            android:hint="id"
            android:id="@+id/e1"
            android:layout_weight="1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
        <EditText
            android:singleLine="true"
            android:maxLines="1"
            android:hint="name"
            android:layout_marginLeft="10dp"
            android:id="@+id/e2"
            android:layout_weight="1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
        <EditText
            android:singleLine="true"
            android:maxLines="1"
            android:hint="age"
            android:layout_marginLeft="10dp"
            android:id="@+id/e3"
            android:layout_weight="1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
        <Button
            android:layout_weight="1"
            android:text="插入"
            android:id="@+id/btn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </LinearLayout>

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

        <EditText
            android:gravity="center"
            android:hint="id"
            android:id="@+id/edit_del"
            android:layout_weight="1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <Button
            android:text="删除"
            android:id="@+id/button_del"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

    </LinearLayout>

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

        <EditText
            android:gravity="center"
            android:hint="old"
            android:id="@+id/edit_updataid"
            android:layout_weight="1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <EditText
            android:gravity="center"
            android:hint="new"
            android:id="@+id/edit_updatastr"
            android:layout_weight="1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <Button
            android:text="改"
            android:id="@+id/button_updata"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

    </LinearLayout>

    <Button
        android:text="查询数据库"
        android:id="@+id/button_read"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <ListView
        android:id="@+id/lv"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </ListView>

</LinearLayout>
  • 9
    点赞
  • 47
    收藏
    觉得还不错? 一键收藏
  • 10
    评论
好的,下面是一个简单的示例代码,演示如何使用Python创建SQLite3数据库并添加查改功能: ```python import sqlite3 class Database: def __init__(self, dbname): self.conn = sqlite3.connect(dbname) self.cur = self.conn.cursor() self.cur.execute("CREATE TABLE IF NOT EXISTS items (id INTEGER PRIMARY KEY, name TEXT, price REAL)") self.conn.commit() def insert(self, name, price): self.cur.execute("INSERT INTO items VALUES (NULL,?,?)", (name, price)) self.conn.commit() return self.cur.lastrowid def view(self): self.cur.execute("SELECT * FROM items") rows = self.cur.fetchall() return rows def search(self, name="", price=""): self.cur.execute("SELECT * FROM items WHERE name=? OR price=?", (name, price)) rows = self.cur.fetchall() return rows def delete(self, id): self.cur.execute("DELETE FROM items WHERE id=?", (id,)) self.conn.commit() def update(self, id, name, price): self.cur.execute("UPDATE items SET name=?, price=? WHERE id=?", (name, price, id)) self.conn.commit() def __del__(self): self.conn.close() # Usage example if __name__ == '__main__': db = Database('mydatabase.db') db.insert("apple", 0.5) db.insert("banana", 0.3) db.insert("orange", 0.8) print(db.view()) print(db.search(name="apple")) db.update(1, "apple", 0.6) print(db.view()) db.delete(2) print(db.view()) ``` 这个示例代码中,我们创建了一个名为“items”的表,有三列:id、name和price。我们还定义了五个方法:insert()、view()、search()、delete()和update(),分别用于向表中插入数据、查看所有数据、根据条件搜索数据、除数据和更新数据。在使用这些方法之前,我们需要先创建一个Database对象,并指定数据库文件名,然后就可以使用这些方法来操作数据了。
评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值