Android SQLite数据库(具体例子)

Android SQLite数据库

1.基本概念
参考自:https://www.runoob.com/w3cnote/android-tutorial-sqlite-intro.html

  1. SQLite是一个轻量级的关系型数据库,运算速度快,占用资源少,很适合在移动设备上使用, 不仅支持标准SQL语法,还遵循ACID(数据库事务)原则,无需账号,使用起来非常方便!
  2. 前面我们学习了使用文件与SharedPreference来保存数据,但是在很多情况下, 文件并不一定是有效的,如多线程并发访问是相关的;app要处理可能变化的复杂数据结构等等! 比如银行的存钱与取钱!使用前两者就会显得很无力或者繁琐,数据库的出现可以解决这种问题, 而Android又给我们提供了这样一个轻量级的SQLite,为何不用?
  3. SQLite支持五种数据类型:NULL,INTEGER,REAL(浮点数),TEXT(字符串文本)和BLOB(二进制对象) 虽然只有五种,但是对于varchar,char等其他数据类型都是可以保存的;因为SQLite有个最大的特点: 你可以各种数据类型的数据保存到任何字段中而不用关心字段声明的数据类型是什么,比如你 可以在Integer类型的字段中存放字符串,当然除了声明为主键INTEGER PRIMARY KEY的字段只能够存储64位整数! 另外, SQLite 在解析CREATE TABLE 语句时, 会忽略 CREATE TABLE 语句中跟在字段名后面的数据类型信息如下面语句会忽略 name字段的类型信息: CREATE TABLE person (personid integer primary key autoincrement, name varchar(20))

相关类:

  • SQLiteOpenHelper:抽象类,我们通过继承该类,然后重写数据库创建以及更新的方法, 我们还可以通过该类的对象获得数据库实例,或者关闭数据库!
  • SQLiteDatabase:数据库访问类:我们可以通过该类的对象来对数据库做一些增删改查的操作
  • Cursor:游标,有点类似于JDBC里的resultset,结果集!可以简单理解为指向数据库中某 一个记录的指针!

2.相关例子
activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<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"
    tools:context=".MainActivity"
    android:background="@drawable/bg"
    android:orientation="vertical"
    >

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:layout_marginTop="200dp"
    android:layout_marginLeft="50dp">
    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="姓 名:"
        android:textSize="30sp"
     />

    <EditText
        android:id="@+id/et_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:hint="请输入姓名"
        android:textSize="20sp"
        >
    </EditText>
</LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_marginLeft="50dp">
        <TextView
            android:id="@+id/phone"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="电 话:"
            android:textSize="30sp"
            />

        <EditText
            android:id="@+id/et_phone"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:hint="请输入手机号码"
            android:textSize="20sp"
            >
        </EditText>
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:gravity="center"
        >
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="添加"
            android:id="@+id/btn_add"
            android:textSize="18sp"
            android:background="#8F92EE"
            >

        </Button>
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="查询"
            android:id="@+id/btn_query"
            android:textSize="18sp"
            android:background="#9D66A8"
            >

        </Button>
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="修改"
            android:id="@+id/btn_update"
            android:textSize="18sp"
            android:background="#F9ACFF"
            >

        </Button>
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="删除"
            android:id="@+id/btn_delete"
            android:textSize="18sp"
            android:background="#ACD6FF"
            >
        </Button>

    </LinearLayout>
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/show"
        android:textSize="20sp"
        android:layout_marginTop="20dp"
        android:textColor="#04F11C">

    </TextView>
</LinearLayout>

MainActivity.java

package com.example.directory;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import static com.example.directory.R.id.btn_add;
import static com.example.directory.R.id.name;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private EditText et_name;
    private EditText et_phone;
    private TextView show;
    private Button btn_add;
    private Button btn_query;
    private Button btn_delete;
    private Button btn_update;
    private MyHelper myHelper;
    private String name;
    private String phone;
    private SQLiteDatabase db;
    private ContentValues values;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        myHelper = new MyHelper(this);
        init();
    }

    private void init() {
        et_name = (EditText)findViewById(R.id.et_name);
        et_phone = (EditText)findViewById(R.id.et_phone);
        show = (TextView)findViewById(R.id.show);
        btn_add = (Button)findViewById(R.id.btn_add);
        btn_query = (Button)findViewById(R.id.btn_query);
        btn_delete = (Button)findViewById(R.id.btn_delete);
        btn_update = (Button)findViewById(R.id.btn_update);
        btn_update.setOnClickListener(this);
        btn_delete.setOnClickListener(this);
        btn_add.setOnClickListener(this);
        btn_query.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_add: //添加数据
                name = et_name.getText().toString();
                phone = et_phone.getText().toString();
                db = myHelper.getReadableDatabase();//获取可读数据库对象

                values = new ContentValues();
                values.put("name",name);
                values.put("phone",phone);
                db.insert("information",null,values);
                db.close();

                break;
            case R.id.btn_query: //查询数据
                db = myHelper.getReadableDatabase();
                Cursor cursor = db.query("information",null,null,null,null,null,null);
                if (cursor.getCount() == 0){
                    show.setText("");
                    Toast.makeText(this,"没有数据",Toast.LENGTH_LONG).show();
                }else{
                    cursor.moveToFirst();
                    show.setText("Name:"+cursor.getString(1)+"     Tel:"+cursor.getString(2));
                }

                while (cursor.moveToNext()){
                    show.append("\n"+"Name:"+cursor.getString(1)+"     Tel:"+cursor.getString(2));
                }
                cursor.close();
                db.close();

                break;

            case R.id.btn_update: //更新数据
                db = myHelper.getWritableDatabase();
                values = new ContentValues();
                values.put("phone",phone=et_phone.getText().toString());
                db.update("information",values,"name=?",new  String[]{et_name.getText().toString()});
                db.close();

                break;
            case R.id.btn_delete: //删除数据
                db = myHelper.getWritableDatabase();
                db.delete("information",null,null);
                Toast.makeText(this,"信息已经删除",Toast.LENGTH_LONG).show();
                show.setText("");
                db.close();

                break;
        }
    }
}

MyHelper.java

package com.example.directory;

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

public class MyHelper extends SQLiteOpenHelper {

    public MyHelper(Context context){
        super(context,"itcast.db",null,1);
    }

    //当数据库第一次创建的时候执行
    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE information (_id INTEGER PRIMARY KEY AUTOINCREMENT ,name VAECHAR(20) ,phone VARCHAR(20))");
    }

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

    }
}

运行截图:
点击添加后查询:
在这里插入图片描述
密码重新输入后点击修改后查询:
在这里插入图片描述
点击删除后查询:
在这里插入图片描述

发布了48 篇原创文章 · 获赞 52 · 访问量 4182

猜你喜欢

转载自blog.csdn.net/weixin_43520670/article/details/105674973