Android数据库SQLite的使用

1.简介

SQLite是一个小巧的嵌入式数据库,它的多数语法和Oracle一样(还好这个学期学了数据库)。SQLiteDataBase是SQLite的数据库管理类,具有创建,删除,执行SQL命令以及执行其他常见数据库管理任务的方法。SQLiteOpenHelper是用于管理数据库创建和版本管理的帮助程序类,是个抽象类,一般我们会创建创建一个子类继承自SQLiteOpenHelper实现onCreate(SQLiteDatabase),onUpgrade(SQLiteDatabase, int, int))。onCreate方法只在第一次打开数据库的时候执行,所以重写这个方法时可以创建表。
Android数据库SQLite的使用_第1张图片

2.例子

创建SQLiteActivity,写好辅助类UserDbHelper继承自SQLiteOpenHelper。

  1. UserInfo.java。包装用户信息。
package xyz.strasae.androidlearn.my.bean;

public class UserInfo {
    public String id;
    public String password;
}
  1. UserDbHelper.java。辅助类。
package xyz.strasae.androidlearn.my;

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

import java.util.ArrayList;

import xyz.strasae.androidlearn.my.bean.UserInfo;

/**
 * 单例模式 确保只打开一次
 */
public class UserDbHelper extends SQLiteOpenHelper {
    private static final String DB_NAME = "user.db";
    private static final int DB_VERSION = 1;
    private static UserDbHelper userDBHelper = null;
    private SQLiteDatabase sqLiteDatabase = null;
    private static final String TABLE_NAME = "user_info";

    /*单例模式 构造器私有*/
    private UserDbHelper(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
    }

    /*单例模式 构造器私有*/
    private UserDbHelper(Context context, int db_version) {
        super(context, DB_NAME, null, db_version);
    }

    /*单例模式 提供对外的接口*/
    public static UserDbHelper getInstance(Context context, int db_version) {
        if(db_version > 0 && userDBHelper == null) {
            userDBHelper = new UserDbHelper(context, db_version);
        } else if(userDBHelper == null) {
            userDBHelper = new UserDbHelper(context);
        }
        return userDBHelper;
    }

    /*打开写连接*/
    public SQLiteDatabase openWriteLink() {
        if(sqLiteDatabase == null || sqLiteDatabase.isOpen() != true) {
            sqLiteDatabase = userDBHelper.getWritableDatabase();
        }
        return sqLiteDatabase;
    }

    /*打开读连接*/
    public SQLiteDatabase openReadLink() {
        if(sqLiteDatabase == null || sqLiteDatabase.isOpen() != true) {
            sqLiteDatabase = userDBHelper.getReadableDatabase();
        }
        return sqLiteDatabase;
    }

    /*关闭连接*/
    public void closeLink() {
        if(sqLiteDatabase != null && sqLiteDatabase.isOpen() == true) {
            sqLiteDatabase.close();
            sqLiteDatabase = null;
        }
    }

    /*获取数据库名称*/
    public String getDbName() {
        if(userDBHelper != null) {
            return userDBHelper.getDatabaseName();
        } else {
            return DB_NAME;
        }
    }

    @Override
    /*创建表*/
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        String drop_sql = "DROP TABLE IF EXISTS " + TABLE_NAME + ";";
        sqLiteDatabase.execSQL(drop_sql);
        String create_sql =  "CREATE TABLE IF NOT EXISTS " + TABLE_NAME + "(_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL," +
                "user_id VARCHAR NOT NULL, password VARCHAR NOT NULL);";
        sqLiteDatabase.execSQL(create_sql);
    }

    @Override
    /*数据库升级,注意一次只能添加一列 第二个参数表示oldVersion 第三个参数表示newVersion*/
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
        if (i1 > 1) {
            String alter_sql = "ALTER TABLE " + TABLE_NAME + " ADD COLUMN " + "phone VARCHAR;";
            sqLiteDatabase.execSQL(alter_sql);
        }
    }

    /*删除指定关键字的记录 condition是where后的条件*/
    public int delete(String condition) {
        return sqLiteDatabase.delete(TABLE_NAME, condition, null);
    }

	/*删除所有记录(0=0是永远成立的)*/
    public int deleteAll() {
        return sqLiteDatabase.delete(TABLE_NAME, "0=0", null);
    }

    /*插入*/
    public long insert(ArrayList infoArrayList) {
        long result = -1;
        for(int i = 0; i < infoArrayList.size(); i++) {
            UserInfo userInfo = infoArrayList.get(i);
            ContentValues contentValues = new ContentValues();
            contentValues.put("user_id", userInfo.id);
            contentValues.put("password", userInfo.password);
            result = sqLiteDatabase.insert(TABLE_NAME, "", contentValues);
        }
        return result;
    }

    public long insert(UserInfo userInfo) {
        ContentValues contentValues = new ContentValues();
        contentValues.put("user_id", userInfo.id);
        contentValues.put("password", userInfo.password);
        return sqLiteDatabase.insert(TABLE_NAME, "", contentValues);
    }

    /*查询*/
    public ArrayList query(String condition) {
        String sql = String.format("select _id,user_id,password" +
                " from %s where %s;", TABLE_NAME, condition);
        ArrayList infoArray = new ArrayList();
        Cursor cursor = sqLiteDatabase.rawQuery(sql, null);
        if(cursor.moveToFirst()) {
            for(;;cursor.moveToNext()) {
                UserInfo userInfo = new UserInfo();
                userInfo.id = cursor.getString(1);
                userInfo.password = cursor.getString(2);
                infoArray.add(userInfo);
                if (cursor.isLast() == true) {
                    break;
                }
            }
        }
        cursor.close();
        return infoArray;
    }
}
  1. activity_sqlite.xml



    
    
        
            

                

                
            

            

                

                
            

            
            
  1. SQLiteActivity.java
package xyz.strasae.androidlearn.my;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;

import xyz.strasae.androidlearn.my.bean.UserInfo;

public class SQLiteActivity extends AppCompatActivity {
    private UserDbHelper userDbHelper;
    private EditText et_id;
    private EditText et_password;
    private TextView tv_show_data;
    private EditText et_input_id;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sqlite);
        et_id = findViewById(R.id.et_id);
        et_password = findViewById(R.id.et_password);
        tv_show_data = findViewById(R.id.tv_show_data);
        et_input_id = findViewById(R.id.et_input_id);
        findViewById(R.id.btn_ok).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(userDbHelper==null) {
                    Toast.makeText(SQLiteActivity.this, "数据库连接为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                userDbHelper.openWriteLink();
                String id = et_id.getText().toString();
                String password = et_password.getText().toString();
                if(TextUtils.isEmpty(id)) {
                    Toast.makeText(SQLiteActivity.this, "请先填写账号!", Toast.LENGTH_SHORT).show();
                    return ;
                } else if(TextUtils.isEmpty(password)){
                    Toast.makeText(SQLiteActivity.this, "密码不能为空!", Toast.LENGTH_SHORT).show();
                    return ;
                }
                UserInfo userInfo = new UserInfo();
                userInfo.id = id;
                userInfo.password = password;
                userDbHelper.insert(userInfo);
                Toast.makeText(SQLiteActivity.this, "存入数据库成功!", Toast.LENGTH_SHORT).show();
            }
        });
        findViewById(R.id.btn_query).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(userDbHelper==null) {
                    Toast.makeText(SQLiteActivity.this, "数据库连接为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                userDbHelper.openReadLink();
                ArrayList userArray = userDbHelper.query("1=1");
                String desc = String.format("数据库查询到%d条记录,详情如下:", userArray.size());
                if(userArray == null || userArray.size() <= 0) {
                    desc = "查询结果为空";
                }
                for (int i=0; i

你可能感兴趣的:(《零基础到App上线》学习笔记,《零基础到App上线》学习笔记)