主要是记笔记给自己看 直接上代码
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的数据要与上面查询出来的结果对应!!!