android studio 连接SQLite数据库并实现增删改查功能

功能代码及调试代码

java 复制代码
package com.example.bankappdemo;

import android.annotation.SuppressLint;
import android.content.ContentValues;
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.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.widget.ListView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;

import pl.com.salsoft.sqlitestudioremote.SQLiteStudioService;


public class CreatAccountActivity extends AppCompatActivity {
    private EditText mCreatConfirmPasswordEditText;
    private EditText mCreatPassWordEditText;
    private EditText mMconfirmPasswordEditText;
    private Button mReturnbutton;
    private Button mConfirmMagbutton;
    private DBHelper mDBHelper;
    private static final String DB_NAME = "Account.db";//数据库名
    private static final String TABLE_NAME = "User";//表名
    private static final String COLUMN_ID = "id";
    private static final String TAG = "CreatAccountActivity";

    public void isNameExist(int id) {//判断用户名是否重复
        try {
            SQLiteStudioService.instance().start(this);
            DBHelper helper = new DBHelper(CreatAccountActivity.this);
            SQLiteDatabase db = helper.getReadableDatabase();
            Cursor cursor = db.rawQuery("select * from User where ID=?", new String[]{"id"});
            cursor.moveToLast();
            if (cursor.getCount() <= 0) {
                Toast.makeText(CreatAccountActivity.this, "用户不存在", Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        Toast.makeText(CreatAccountActivity.this, "用户存在", Toast.LENGTH_SHORT).show();
    }

    //插入数据到数据库
    public void addAccountSQlite(String name, String pwd, int id) {
        SQLiteStudioService.instance().start(this);
        DBHelper helper = new DBHelper(CreatAccountActivity.this);
        SQLiteDatabase db = helper.getReadableDatabase();
        String sql = "insert into User values(" + id + ',' + name + ',' + pwd + ',' + 0.0 + ")";
        db.execSQL(sql);
        db.close();
        Toast.makeText(CreatAccountActivity.this, "账户创建成功", Toast.LENGTH_SHORT).show();
    }

    //删除账户
    public void delAllAccount(int id) {
        SQLiteStudioService.instance().start(this);
        DBHelper helper = new DBHelper(CreatAccountActivity.this);
        SQLiteDatabase db = helper.getWritableDatabase();
        db.delete(TABLE_NAME, "ID=" + id, null);
        //db.close();
        Toast.makeText(CreatAccountActivity.this, "删除所有账户成功", Toast.LENGTH_SHORT).show();
    }

    //更新数据
    public void updateData(String name, String pwd, int id, Double money) {
        SQLiteStudioService.instance().start(this);
        DBHelper helper = new DBHelper(CreatAccountActivity.this);
        SQLiteDatabase db = helper.getWritableDatabase();
        String sql = "update User set name = " + name + " ,password = " + pwd + " ,money = " + money + " where id = " + id;
        db.execSQL(sql);


        Toast.makeText(CreatAccountActivity.this, "更新账户信息成功", Toast.LENGTH_SHORT).show();
    }

    //根据ID查找数据
    public void query(int id) {
        SQLiteStudioService.instance().start(this);
        DBHelper helper = new DBHelper(CreatAccountActivity.this);
        SQLiteDatabase db = helper.getWritableDatabase();
        String rawQuerySql = "select * from " + TABLE_NAME + " where " + COLUMN_ID + " = " + id + " or " + COLUMN_ID + " = 2";
        Log.e(TAG, rawQuerySql);

/**
 *   Cursor cursor = helper.getWritableDatabase().rawQuery(rawQuerySql, null);
 *   int resultCounts = cursor.getCount();
 * 通过执行SQL查询语句获取结果集的行数
 * 通过helper.getWritableDatabase()方法获取可写的SQLiteDatabase对象
 * 使用rawQuery()方法执行查询语句,将结果保存在Cursor对象中
 * 通过调用cursor.getCount()方法获取结果集的行数,将结果保存在resultCounts变量中
 * 最后,可以根据resultCounts的值来判断查询结果的行数
 */
        Cursor cursor = helper.getWritableDatabase().rawQuery(rawQuerySql, null);
        int resultCounts = cursor.getCount();
        //遍历每一行
        for (int i = 0; i < resultCounts; i++) {
            //得到的cursor的初始位置是指向第一条记录的前一个位置的(-1),避免出现下标越界异常,使用moveToNext:移动游标到下一条记录,也就是第一条记录
            cursor.moveToNext();
            Account stAccount = new Account();
            int nId = cursor.getInt(0);//ID是第一列
            String strUsername = cursor.getString(1);//名字是第二列
            String strPassword = cursor.getString(2);//密码是第三列
            Double dMoney = cursor.getDouble(3);//余额是第四列

            stAccount.setId(nId);
            stAccount.setUserName(strUsername);
            stAccount.setPassWord(strPassword);
            stAccount.setMoney(dMoney);

            Log.e(TAG, stAccount.toString());

        }
        Toast.makeText(CreatAccountActivity.this, "信息查询成功", Toast.LENGTH_SHORT).show();

    }

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.creataccount);


        mConfirmMagbutton = findViewById(R.id.confirmMagbutton);
        mConfirmMagbutton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //调试信息
                String name = ((EditText) findViewById(R.id.creatUserNameEditText)).getText().toString();
                String pwd = ((EditText) findViewById(R.id.creatPassWordEditText)).getText().toString();
                int id = 3;
                //ContentValues values = new ContentValues();
                // addAccountSQlite(name, pwd, id);
                //  delAllAccount(1);
               updateData("2","2",2,6000.00);
               // query(3);

                //  isNameExist(1);

            }
        });
    }
}

DBHelper类

java 复制代码
package com.example.bankappdemo;

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

public class DBHelper extends SQLiteOpenHelper {
    private static final String TAG = "DBHelper";

    private Context context;//上下文环境
    private static final String DB_NAME = "Account.db";//数据库名
    private static final int DB_VERSION = 1;//数据库版本号
    private static final String TABLE_NAME = "User";//表名
    private Context mContext;
    // 列名称
    private static final String COLUMN_ID = "id";
    private static final String COLUMN_NAME = "name";
    private static final String COLUMN_PASSWORD = "password";
    private static final String COLUMN_MONEY = "money";

    public DBHelper(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // 创建数据库表
        String createTableQuery = "create table if not exists " + TABLE_NAME + "(" + COLUMN_ID +" int primary key, " + COLUMN_NAME + " varchar, " + COLUMN_PASSWORD + " varchar, " + COLUMN_MONEY + " double)";

        Log.e(TAG, "建表语句:" + createTableQuery);

        db.execSQL(createTableQuery);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // 升级数据库版本
        if (oldVersion < newVersion) {
            // 执行升级操作,例如添加新的表或修改表结构
        }
    }

}
相关推荐
时差95327 分钟前
【面试题】Hive 查询:如何查找用户连续三天登录的记录
大数据·数据库·hive·sql·面试·database
让学习成为一种生活方式29 分钟前
R包下载太慢安装中止的解决策略-R语言003
java·数据库·r语言
秋意钟1 小时前
MySQL日期类型选择建议
数据库·mysql
Dxy12393102162 小时前
python下载pdf
数据库·python·pdf
桀桀桀桀桀桀2 小时前
数据库中的用户管理和权限管理
数据库·mysql
superman超哥3 小时前
04 深入 Oracle 并发世界:MVCC、锁、闩锁、事务隔离与并发性能优化的探索
数据库·oracle·性能优化·dba
用户8007165452003 小时前
HTAP数据库国产化改造技术可行性方案分析
数据库
engchina4 小时前
Neo4j 和 Python 初学者指南:如何使用可选关系匹配优化 Cypher 查询
数据库·python·neo4j
engchina4 小时前
使用 Cypher 查询语言在 Neo4j 中查找最短路径
数据库·neo4j
尘浮生4 小时前
Java项目实战II基于Spring Boot的光影视频平台(开发文档+数据库+源码)
java·开发语言·数据库·spring boot·后端·maven·intellij-idea