Android SQLite: déclaration de mise à jour

Je dois implémenter SQLite dans mon application. J’ai suivi ce tutoriel .. Création et utilisation de bases de données sous Android

Tout fonctionne bien. J’ai inséré 1 rangée avec 5 colonnes. Maintenant, je veux mettre à jour la valeur de 1 colonne uniquement et les autres restront les mêmes.

Il existe une méthode de mise à jour dans le didacticiel, mais elle nécessite tous les parameters, mais je ne souhaite mettre à jour qu’une seule colonne.

Vous pouvez utiliser le code ci-dessous.

Ssortingng strFilter = "_id=" + Id; ContentValues args = new ContentValues(); args.put(KEY_TITLE, title); myDB.update("titles", args, strFilter, null); 

Tu peux essayer:

 db.execSQL("UPDATE DB_TABLE SET YOUR_COLUMN='newValue' WHERE id=6 "); 

Ou

 ContentValues newValues = new ContentValues(); newValues.put("YOUR_COLUMN", "newValue"); db.update("YOUR_TABLE", newValues, "id=6", null); 

Ou

 ContentValues newValues = new ContentValues(); newValues.put("YOUR_COLUMN", "newValue"); Ssortingng[] args = new Ssortingng[]{"user1", "user2"}; db.update("YOUR_TABLE", newValues, "name=? OR name=?", args); 

Tout est dans le tutoriel comment faire cela:

  ContentValues args = new ContentValues(); args.put(columnName, newValue); db.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null); 

Utilisez ContentValues pour définir les colonnes mises à jour et la méthode update() dans laquelle vous devez spécifier la table et un critère pour mettre à jour uniquement les lignes que vous souhaitez mettre à jour.

vous pouvez toujours exécuter SQL.

 update [your table] set [your column]=value 

par exemple

 update Foo set Bar=125 

L’object SQLiteDatabase dépend du type d’opération sur la firebase database.

Plus d’informations, visitez le site officiel:

https://developer.android.com/training/basics/data-storage/databases.html#UpdateDbRow

Il explique comment manipuler les consultations sur la firebase database SQLite.

INSERT ROW

Obtient le référentiel de données en mode écriture

 SQLiteDatabase db = mDbHelper.getWritableDatabase(); 

Créer une nouvelle carte de valeurs, où les noms de colonne sont les clés

 ContentValues values = new ContentValues(); values.put(FeedEntry.COLUMN_NAME_ENTRY_ID, id); values.put(FeedEntry.COLUMN_NAME_TITLE, title); values.put(FeedEntry.COLUMN_NAME_CONTENT, content); 

Insérer la nouvelle ligne en renvoyant la valeur de la clé primaire de la nouvelle ligne

 long newRowId; newRowId = db.insert( FeedEntry.TABLE_NAME, FeedEntry.COLUMN_NAME_NULLABLE, values); 

UPDATE ROW

Définir la partie “où” de la requête.

 Ssortingng selection = FeedEntry.COLUMN_NAME_ENTRY_ID + " LIKE ?"; 

Spécifiez les arguments dans l’ordre réservé.

 Ssortingng[] selectionArgs = { Ssortingng.valueOf(rowId) }; SQLiteDatabase db = mDbHelper.getReadableDatabase(); 

Nouvelle valeur pour une colonne

 ContentValues values = new ContentValues(); values.put(FeedEntry.COLUMN_NAME_TITLE, title); 

Quelle ligne mettre à jour en fonction de l’ID

 Ssortingng selection = FeedEntry.COLUMN_NAME_ENTRY_ID + " LIKE ?"; Ssortingng[] selectionArgs = { Ssortingng.valueOf(rowId) }; int count = db.update( FeedReaderDbHelper.FeedEntry.TABLE_NAME, values, selection, selectionArgs); 

J’utilise cette classe pour gérer la firebase database. J’espère que cela aidera certains à l’avenir.

Heureux codage

 public class Database { private static class DBHelper extends SQLiteOpenHelper { /** * Database name */ private static final Ssortingng DB_NAME = "db_name"; /** * Table Names */ public static final Ssortingng TABLE_CART = "DB_CART"; /** * Cart Table Columns */ public static final Ssortingng CART_ID_PK = "_id";// Primary key public static final Ssortingng CART_DISH_NAME = "dish_name"; public static final Ssortingng CART_DISH_ID = "menu_item_id"; public static final Ssortingng CART_DISH_QTY = "dish_qty"; public static final Ssortingng CART_DISH_PRICE = "dish_price"; /** * Ssortingng to create reservation tabs table */ private final Ssortingng CREATE_TABLE_CART = "CREATE TABLE IF NOT EXISTS " + TABLE_CART + " ( " + CART_ID_PK + " INTEGER PRIMARY KEY, " + CART_DISH_NAME + " TEXT , " + CART_DISH_ID + " TEXT , " + CART_DISH_QTY + " TEXT , " + CART_DISH_PRICE + " TEXT);"; public DBHelper(Context context) { super(context, DB_NAME, null, 2); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(CREATE_TABLE_CART); } @Override public void onUpgrade(SQLiteDatabase db, int arg1, int arg2) { db.execSQL("DROP TABLE IF EXISTS " + CREATE_TABLE_CART); onCreate(db); } } /** * CART handler */ public static class Cart { /** * Check if Cart is available or not * * @param context * @return */ public static boolean isCartAvailable(Context context) { DBHelper dbHelper = new DBHelper(context); SQLiteDatabase db = dbHelper.getReadableDatabase(); boolean exists = false; try { Ssortingng query = "SELECT * FROM " + DBHelper.TABLE_CART; Cursor cursor = db.rawQuery(query, null); exists = (cursor.getCount() > 0); cursor.close(); db.close(); } catch (SQLiteException e) { db.close(); } return exists; } /** * Insert values in cart table * * @param context * @param dishName * @param dishPrice * @param dishQty * @return */ public static boolean insertItem(Context context, Ssortingng itemId, Ssortingng dishName, Ssortingng dishPrice, Ssortingng dishQty) { DBHelper dbHelper = new DBHelper(context); SQLiteDatabase db = dbHelper.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(DBHelper.CART_DISH_ID, "" + itemId); values.put(DBHelper.CART_DISH_NAME, "" + dishName); values.put(DBHelper.CART_DISH_PRICE, "" + dishPrice); values.put(DBHelper.CART_DISH_QTY, "" + dishQty); try { db.insert(DBHelper.TABLE_CART, null, values); db.close(); return true; } catch (SQLiteException e) { db.close(); return false; } } /** * Check for specific record by name * * @param context * @param dishName * @return */ public static boolean isItemAvailable(Context context, Ssortingng dishName) { DBHelper dbHelper = new DBHelper(context); SQLiteDatabase db = dbHelper.getReadableDatabase(); boolean exists = false; Ssortingng query = "SELECT * FROM " + DBHelper.TABLE_CART + " WHERE " + DBHelper.CART_DISH_NAME + " = '" + Ssortingng.valueOf(dishName) + "'"; try { Cursor cursor = db.rawQuery(query, null); exists = (cursor.getCount() > 0); cursor.close(); } catch (SQLiteException e) { e.printStackTrace(); db.close(); } return exists; } /** * Update cart item by item name * * @param context * @param dishName * @param dishPrice * @param dishQty * @return */ public static boolean updateItem(Context context, Ssortingng itemId, Ssortingng dishName, Ssortingng dishPrice, Ssortingng dishQty) { DBHelper dbHelper = new DBHelper(context); SQLiteDatabase db = dbHelper.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(DBHelper.CART_DISH_ID, itemId); values.put(DBHelper.CART_DISH_NAME, dishName); values.put(DBHelper.CART_DISH_PRICE, dishPrice); values.put(DBHelper.CART_DISH_QTY, dishQty); try { Ssortingng[] args = new Ssortingng[]{dishName}; db.update(DBHelper.TABLE_CART, values, DBHelper.CART_DISH_NAME + "=?", args); db.close(); return true; } catch (SQLiteException e) { db.close(); return false; } } /** * Get cart list * * @param context * @return */ public static ArrayList getCartList(Context context) { DBHelper dbHelper = new DBHelper(context); SQLiteDatabase db = dbHelper.getReadableDatabase(); ArrayList cartList = new ArrayList<>(); try { String query = "SELECT * FROM " + DBHelper.TABLE_CART + ";"; Cursor cursor = db.rawQuery(query, null); for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) { cartList.add(new CartModel( cursor.getString(cursor.getColumnIndex(DBHelper.CART_DISH_ID)), cursor.getString(cursor.getColumnIndex(DBHelper.CART_DISH_NAME)), cursor.getString(cursor.getColumnIndex(DBHelper.CART_DISH_QTY)), Integer.parseInt(cursor.getString(cursor.getColumnIndex(DBHelper.CART_DISH_PRICE))) )); } db.close(); } catch (SQLiteException e) { db.close(); } return cartList; } /** * Get total amount of cart items * * @param context * @return */ public static String getTotalAmount(Context context) { DBHelper dbHelper = new DBHelper(context); SQLiteDatabase db = dbHelper.getReadableDatabase(); double totalAmount = 0.0; try { String query = "SELECT * FROM " + DBHelper.TABLE_CART + ";"; Cursor cursor = db.rawQuery(query, null); for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) { totalAmount = totalAmount + Double.parseDouble(cursor.getString(cursor.getColumnIndex(DBHelper.CART_DISH_PRICE))) * Double.parseDouble(cursor.getString(cursor.getColumnIndex(DBHelper.CART_DISH_QTY))); } db.close(); } catch (SQLiteException e) { db.close(); } if (totalAmount == 0.0) return ""; else return "" + totalAmount; } /** * Get item quantity * * @param context * @param dishName * @return */ public static String getItemQty(Context context, String dishName) { DBHelper dbHelper = new DBHelper(context); SQLiteDatabase db = dbHelper.getReadableDatabase(); Cursor cursor = null; String query = "SELECT * FROM " + DBHelper.TABLE_CART + " WHERE " + DBHelper.CART_DISH_NAME + " = '" + dishName + "';"; String quantity = "0"; try { cursor = db.rawQuery(query, null); if (cursor.getCount() > 0) { cursor.moveToFirst(); quantity = cursor.getSsortingng(cursor .getColumnIndex(DBHelper.CART_DISH_QTY)); return quantity; } } catch (SQLiteException e) { e.printStackTrace(); } return quantity; } /** * Delete cart item by name * * @param context * @param dishName */ public static void deleteCartItem(Context context, Ssortingng dishName) { DBHelper dbHelper = new DBHelper(context); SQLiteDatabase db = dbHelper.getReadableDatabase(); try { Ssortingng[] args = new Ssortingng[]{dishName}; db.delete(DBHelper.TABLE_CART, DBHelper.CART_DISH_NAME + "=?", args); db.close(); } catch (SQLiteException e) { db.close(); e.printStackTrace(); } } }//End of cart class /** * Delete database table * * @param context */ public static void deleteCart(Context context) { DBHelper dbHelper = new DBHelper(context); SQLiteDatabase db = dbHelper.getReadableDatabase(); try { db.execSQL("DELETE FROM " + DBHelper.TABLE_CART); } catch (SQLiteException e) { e.printStackTrace(); } } 

}

Usage:

  if(Database.Cart.isCartAvailable(context)){ Database.deleteCart(context); }