关于一些android数据库的创建

主要是记笔记给自己看 直接上代码

private static final String DB_NAME = "account.db";


   
    public Context context;


   
    SQLiteDatabase db;


   
   public DBHelper(Context context) {
       
  this.context = context.getApplicationContext();
       
   String dbPath = Constant.DB_PATH.concat(File.separator).concat(DB_NAME);
     
    File file = new File(Constant.DB_PATH);
       
  if(!file.exists()){
            file.mkdirs();
       
   }
       
  //db = SQLiteDatabase.openOrCreateDatabase(dbPath, null);
       
  db = SQLiteDatabase.openOrCreateDatabase(context.getFilesDir().toString() + "/" + DB_NAME, null);
       
 createTable(db);
   
    }

db的生成路径可以自己定义  context.getFilesDir().toString() 是将db放在data/data/包名/file  文件夹下

/**
     * 生成数据库表
     * @param db
     */
    private void createTable(SQLiteDatabase db) {
        if (db == null){
            return;
        }
        String sql = "CREATE TABLE IF NOT EXISTS " + AccountEntity.TABLE_NAME + " ("
                + "id TEXT PRIMARY KEY,"
                + AccountEntity.USER_NAME + " TEXT,"
                + AccountEntity.USER_PWD + " TEXT,"
                + AccountEntity.LAST_CLOSE_TIME + " TEXT,"
                + AccountEntity.ROLE_ID + " INTEGER);";
        db.execSQL(sql);
    }


    /**
     * 根据用户名和角色查询
     * @param user_name
     * @param roleId
     * @return
     */
    public List<AccountEntity> query(String user_name, int roleId){
        StringBuffer buffer = new StringBuffer();
        buffer.append("select ")
                .append(AccountEntity.USER_NAME).append(",")
                .append(AccountEntity.USER_PWD).append(",")
                .append(AccountEntity.ROLE_ID)
                .append(" from ").append(AccountEntity.TABLE_NAME)
                .append(" where ").append(AccountEntity.USER_NAME).append("='").append(user_name).append("'");


        if (roleId > 0){
            buffer.append(" and ").append(AccountEntity.ROLE_ID).append("=").append(roleId);
        }


        Cursor cursor = db.rawQuery(buffer.toString(), null);
        List<AccountEntity> accounts = new ArrayList<>();
        while (cursor.moveToNext()){
            AccountEntity entity = new AccountEntity();
            entity.setUserName(cursor.getString(0));
            entity.setPassword(cursor.getString(1));
            entity.setRoleId(cursor.getInt(2));


            accounts.add(entity);
        }
        cursor.close();
        return accounts;
    }

    下面set的数据要与上面查询出来的结果对应!!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值