Android SQLite:更新声明


91

我需要在我的应用程序中实现SQLite。我遵循了本教程。 在Android中创建和使用数据库

一切正常。我插入1行5列。现在,我只想更新1列的值,其他值将保持不变。

教程中有一种更新方法,但是它需要所有参数,但是我只想更新一列。


在此服务器上找不到所请求的URL /index.php/articlesdatastorage/235-android-one中创建和使用数据库。
马查多

Answers:


165

您可以使用以下代码。

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

13
您甚至可以这样做:myDB.update(“ titles”,args,strFilter,new String [] {Integer.toString(ID)}); 如果将strFilter设置为“ _id =?” ...单个项目的烦人之处在于您仍然需要将其放入数组中,这可能会带来不便。尽管如此,仍投票赞成正确的答案。
joshhendo 2012年

4
@Dheeraj-这只会更新添加到ContentValues对象的列
Simonw 2012年

2
如果我没有记错的话,@joshhendo的代码还应该防止SQL注入,但此答案没有考虑。由于参数作为参数传递,因此底层代码对​​其进行了转义。
r41n 2014年

您将需要在报价单周围加上引号Id。像这样的东西:String strFilter = "_id='" + Id + "'";
Guillaume

119

你可以试试:

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

要么

ContentValues newValues = new ContentValues();
newValues.put("YOUR_COLUMN", "newValue");

db.update("YOUR_TABLE", newValues, "id=6", null);

要么

ContentValues newValues = new ContentValues();
newValues.put("YOUR_COLUMN", "newValue");

String[] args = new String[]{"user1", "user2"};
db.update("YOUR_TABLE", newValues, "name=? OR name=?", args);

53

本教程中的全部内容是如何做到的:

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

使用ContentValues设置更新的列,比update()方法,你必须specifiy,桌子和一个标准只更新要更新的行。


-1。问题是要更新一行中的单个列,而不要更新整个行。亚历克斯的答案是正确的。
Dheeraj Vepakomma 2012年

7
Dheeraj,您可以根据需要添加任意多个args.put(columnName,newValue)。
西蒙·罗林

18

您可以随时执行SQL。

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

例如

update Foo set Bar=125

3
如果有一个(非常简单方便)的API,为什么还要使用显式的SQL语句?
斯蒂芬

3
@Stephan:因为它不是标准的SQLite。当数据库在不同平台上的应用程序之间共享时,API占用的空间特别大
Rafael Nobre

@Stephan这是问题的唯一正确答案。OP希望更新一行中的单个列,而不是更新整个行。
Dheeraj Vepakomma 2012年

在这里使用API​​是更好的选择,我很惊讶没有中间的解决方案,C库可让您定义要执行的SQL并设置格式化程序和令牌,下一步是使用C api将变量绑定到SQL字符串中的标记,从而避免了解析错误和引用问题等...在这里,它几乎是非常有帮助的,甚至没有编写SQL的一部分,感觉也不好...而是连接了SQL字符串。
丹尼尔(Daniel)

当字符串包含单引号和某些特殊字符时,此方法将失败。@Nike的答案是正确的。
2012年

1

SQLiteDatabase对象取决于数据库上的操作类型。

更多信息,请访问官方网站:

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

它说明了如何在SQLite数据库上处理咨询。

插入行

以写模式获取数据存储库

SQLiteDatabase db = mDbHelper.getWritableDatabase();

创建一个新的值映射,其中列名是键

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);

插入新行,返回新行的主键值

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

更新行

定义查询的“ where”部分。

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

按占位符顺序指定参数。

String[] selectionArgs = { String.valueOf(rowId) };


SQLiteDatabase db = mDbHelper.getReadableDatabase();

一栏的新值

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

根据ID更新哪一行

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

尽管链接的网站可能包含问题的答案,但您的答案似乎不完整。链接可能以其他方式过期或中断。请从链接的网站中添加相关代码/信息至您的答案。
迈克,

当然,我知道,我只是从字面上提出了对我
有用

1

我用这个类来处理数据库,希望对将来有帮助。

快乐的编码。

public class Database {

private static class DBHelper extends SQLiteOpenHelper {

    /**
     * Database name
     */
    private static final String DB_NAME = "db_name";

    /**
     * Table Names
     */
    public static final String TABLE_CART = "DB_CART";


    /**
     *  Cart Table Columns
     */
    public static final String CART_ID_PK = "_id";// Primary key

    public static final String CART_DISH_NAME = "dish_name";
    public static final String CART_DISH_ID = "menu_item_id";
    public static final String CART_DISH_QTY = "dish_qty";
    public static final String CART_DISH_PRICE = "dish_price";

    /**
     * String to create reservation tabs table
     */
    private final String 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 {
            String 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, String itemId, String dishName, String dishPrice, String 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, String dishName) {

        DBHelper dbHelper = new DBHelper(context);
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        boolean exists = false;

        String query = "SELECT * FROM " + DBHelper.TABLE_CART + " WHERE "
                + DBHelper.CART_DISH_NAME + " = '" + String.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, String itemId, String dishName, String dishPrice, String 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 {

            String[] args = new String[]{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<CartModel> getCartList(Context context) {

        DBHelper dbHelper = new DBHelper(context);
        SQLiteDatabase db = dbHelper.getReadableDatabase();

        ArrayList<CartModel> 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.getString(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, String dishName) {
        DBHelper dbHelper = new DBHelper(context);
        SQLiteDatabase db = dbHelper.getReadableDatabase();

        try {

            String[] args = new String[]{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();
    }

}

}

用法:

  if(Database.Cart.isCartAvailable(context)){

       Database.deleteCart(context);

   }
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.