在Android Studio中操作SQLite数据库

项目目录:

在Android Studio中操作SQLite数据库_第1张图片

首先对页面做一个简单的布局

在Android Studio中操作SQLite数据库_第2张图片

activity_main.xml代码如下:




    

    

    

    

编写MySQLiteHelper类

package com.example.sqlitedemo;

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



/**
 * 安卓数据库调用
 * 1.建立SQLiteOpenHelper类,然后将参数填好
 * */
public class MySQLiteHelper extends SQLiteOpenHelper {

    private static  final String CREATE_USER_TABLE = "create table user(id integer primary key autoincrement,username text,password text)";

    /**
     * 构造方法,你可以联想到创建了一个数据,类似于MySQL的建库语句
     *用于创建数据库,并配置数据库信息
     * */
    public MySQLiteHelper(Context context) {
        //构造方法的四个参数:1.上下文 2.数据库名字 3.数据库工厂直接null就可以,4.数据库版本
        super(context, "user.db", null, 1);
    }

    /**
     * 用于建表或者执行sql语句,但是没有返回值因此不推荐调用增删改查sql语句,只推荐用来建表
     * SQLiteDatabase--->SQLite数据库(Java类)
     * */
    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        //调用执行sql语句
        sqLiteDatabase.execSQL(CREATE_USER_TABLE);

    }

    /**
     * 用于做数据库升级的方法,如果数据库的表或者表结构表以及数据关系都发生改变则需要在这里升级
     * */
    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

    }
}

UserDao代码如下:

package com.example.sqlitedemo;


import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

/**
 * 数据库访问对象
 * DAO:DATEBASE ACCESS OBJECT
 * 是控制层于数据库交互的中间层,用于做数据库的增删改查具体实现
 * */
public class UserDao {
    //SQLiteDatabase对象封装了所有SQLite的增删改查语句的操作方法,让开发者直接调用就行
    private SQLiteDatabase sqLiteDatabase;

    public UserDao(Context context){
        //初始化刚刚写的MySQLiteHelper对象
        MySQLiteHelper mySQLiteHelper = new MySQLiteHelper(context);
        //获取sqLiteDatabase对象
        sqLiteDatabase = mySQLiteHelper.getWritableDatabase();
    }

    /**
     * 插入一条记录进入user表
     * insert into user("username","password") values("zhangsan","123456");
     * */
    public boolean insertUser(String username,String password){
        ContentValues values = new ContentValues();
        values.put("username",username);
        values.put("password",password);

        //第一个是表名,第二个null,第三个是相当于sql插入语句的values
        //id用于判断是否插入成功: 如果大于0则表示插入了至少一条数据,否则插入失败
        long id = sqLiteDatabase.insert("user",null,values);
        return id>0?true:false;
    }

    /**
     * 查询记录
     * select * from user where username = "zhangsan";
     * */
    public UserBean querryUser(String username,String password){

        Cursor cursor = sqLiteDatabase.query("user",new String[]{"username","password"},"username=? and password=?",new String[]{username,password},null,null,null);

        UserBean userBean = new UserBean();
        while (cursor.moveToNext()){
           //userBean.setId(cursor.getInt(cursor.getColumnIndex("id")));
            userBean.setUsername(cursor.getString(cursor.getColumnIndex("username")));
            userBean.setPassword(cursor.getString(cursor.getColumnIndex("password")));
            Log.e("tag",userBean.getId()+"|"+userBean.getUsername()+"|"+userBean.getPassword());
        }
        return userBean;
    }

    /**
     * 修改数据库表记录
     * update user set password = 123123 where username = zhangsan
     * */
    public boolean updateUser(String username,String newpassword){
        boolean flag;
        ContentValues values = new ContentValues();
        values.put("password",newpassword);
        long id = sqLiteDatabase.update("user",values,"username = ? ",new String[]{username});
        flag = id > 0?true : false;
        return flag;
    }



    /**
     * 删除
     * delete from user where username = "xxx"
     * */
    public boolean deleteUser(String username){
        long id = sqLiteDatabase.delete("user","username = ?",new String[]{username});
        return id>0?true:false;
    }
}

UserBean代码如下:

package com.example.sqlitedemo;

public class UserBean {

    private int id;
    private String username;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    private String password;
}

MainActivity代码如下:

package com.example.sqlitedemo;

import androidx.appcompat.app.AppCompatActivity;

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

public class MainActivity extends AppCompatActivity {

    Button btnlogin,btnregist,btnupdate,btndelete;
    EditText etUname,etUpwd,etChange;
    UserDao userDao;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        userDao = new UserDao(this);
        etChange = findViewById(R.id.et_uppassword);
        etUname = findViewById(R.id.et_username);
        etUpwd = findViewById(R.id.et_password);
        btndelete = findViewById(R.id.btn_delete);
        btnlogin = findViewById(R.id.btn_login);
        btnregist = findViewById(R.id.btn_regist);
        btnupdate = findViewById(R.id.btn_update);

        btnregist.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String username = etUname.getText().toString();
                String password = etUpwd.getText().toString();
                boolean flag = userDao.insertUser(username,password);
                if(flag){
                    Toast.makeText(getApplicationContext(),"注册成功",Toast.LENGTH_SHORT).show();
                }else {
                    Toast.makeText(getApplicationContext(),"注册失败",Toast.LENGTH_SHORT).show();
                }
            }
        });

        btnlogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String username = etUname.getText().toString();
                String password = etUpwd.getText().toString();
                UserBean userBean = userDao.querryUser(username,password);
                if(TextUtils.isEmpty(userBean.getUsername())){
                    Toast.makeText(getApplicationContext(),"登录失败",Toast.LENGTH_SHORT).show();
                }else {
                    Toast.makeText(getApplicationContext(),"登录成功",Toast.LENGTH_SHORT).show();
                }
            }
        });

        btnupdate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String username = etUname.getText().toString();
                String password = etChange.getText().toString();
                boolean flag = userDao.updateUser(username,password);
                if(flag){
                    Toast.makeText(getApplicationContext(),"修改成功",Toast.LENGTH_SHORT).show();
                }else {
                    Toast.makeText(getApplicationContext(),"修改失败",Toast.LENGTH_SHORT).show();
                }
            }
        });


        btndelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String username = etUname.getText().toString();
                boolean flag = userDao.deleteUser(username);
                if(flag){
                    Toast.makeText(getApplicationContext(),"删除成功",Toast.LENGTH_SHORT).show();
                }else {
                    Toast.makeText(getApplicationContext(),"删除失败",Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
}

你可能感兴趣的:(Android,android)