Code example for SQLiteDatabase

Methods: execSQLupdate

1
	 
	private void resetDefaultAccount(SQLiteDatabase sqLiteDatabase) {
		StringBuilder sql = new StringBuilder();
		sql.append(" update Account set Is_Default = 0 ");
		sql.append(" where Is_Default = 1");
		sqLiteDatabase.execSQL(sql.toString());
	} 
	 
	private void clearDeletedAccount(SQLiteDatabase sqLiteDatabase, Account account) {
		StringBuilder whereClause = new StringBuilder();
		whereClause.append(" State = ").append(Account.STATE_INVALID);
		whereClause.append(" and Service_Provider = ").append(account.getServiceProviderNo());
		whereClause.append(" and User_Id = '").append(account.getUserId()).append("'");
		sqLiteDatabase.delete(TABLE, whereClause.toString(), null);
	} 
 
	public int update(Account account) {
		if (isNull(account)) {
			return -1; 
		} 
 
		SQLiteDatabase sqLiteDatabase = dbHelper.getWritableDatabase();
		sqLiteDatabase.beginTransaction();
 
		int rowsAffected = 0;
		try { 
			rowsAffected = update(sqLiteDatabase, account);
			sqLiteDatabase.setTransactionSuccessful();
		} finally { 
			sqLiteDatabase.endTransaction();
		} 
 
		return rowsAffected;
	} 
 
	/*package*/ int update(SQLiteDatabase sqLiteDatabase, Account account) {
		if (isNull(account)) {
			return -1; 
		} 
 
		ContentValues values = new ContentValues();
		values.put("Access_Token",
			EncryptUtil.desEncrypt(account.getAccessToken(), Constants.KEY_BYTES));
		values.put("Access_Secret",
			EncryptUtil.desEncrypt(String.valueOf(account.getAccessSecret()), Constants.KEY_BYTES));
		values.put("Auth_Version", account.getAuthVersion());
		values.put("Service_Provider", account.getServiceProvider().getSpNo());
		values.put("User_ID", account.getUser().getUserId());
		values.put("Screen_Name", account.getUser().getScreenName());
		values.put("App_Key", String.valueOf(account.getAppKey()));
		values.put("App_Secret", String.valueOf(account.getAppSecret()));
		values.put("State", account.getState());
		values.put("Is_Default", account.isDefault());
		values.put("Rest_Proxy_Url", account.getRestProxyUrl());
		values.put("Search_Proxy_Url", account.getSearchProxyUrl());
		values.put("Token_Expired_At",
				account.getTokenExpiredAt() == null? -1L : account.getTokenExpiredAt().getTime());
 
		if (account.isDefault()) {
			resetDefaultAccount(sqLiteDatabase);  // 清除原有的默认帐号状态设置
		} 
		 
		if (account.getUser() != null) {
			userDao.save(sqLiteDatabase,account.getUser());
		} 
		int rowsAffected = sqLiteDatabase.update(TABLE, values,
			"Account_ID = " + account.getAccountId(), null);
 
		return rowsAffected;
	}