使用 database.query() 在 SQlite 和 Android 中插入或更新; [英] Insert or update in SQlite and Android using the database.query();

查看:17
本文介绍了使用 database.query() 在 SQlite 和 Android 中插入或更新;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法改变我的功能:

is there a way to change my function:

public categorie createCategoria(String categoria) {
            ContentValues values = new ContentValues();
            values.put(MySQLiteHelper.COLUMN_NOME, categoria);
            values.put(MySQLiteHelper.COLUMN_PREF, 0);

            long insertId = database.insert(MySQLiteHelper.TABLE_CATEGORIE, null,
                values);

            Cursor cursor = database.query(MySQLiteHelper.TABLE_CATEGORIE,
                allCategorieColumns, MySQLiteHelper.COLUMN_ID + " = " + insertId, null,
                null, null, null);
            cursor.moveToFirst();
            categorie newCategoria = cursorToCategorie(cursor);
            cursor.close();
            return newCategoria;
          } 

这是一个原始插入,我想更改此函数以使其相应更新或插入.我想更改它,因为我已经在某些地方使用此功能,但现在我需要选择是插入一行还是更新(或忽略插入)具有相同 COLUMN_NOME 的行.有人可以帮我做这个吗?

this is a raw insert, i would like to change this function to make it update or insert accordingly. i would like to change this becouse i'm already using this function in some places, but now i need to choose if insert a row or update (or ignoring the insert) a row with the same COLUMN_NOME. can someone help me doing this?

我的意思是,只有在没有另一个同名的行时,我才想插入一个新行(如您所知).

i mean i would like to insert a new row ONLY if there isn't another with the same name (as usual you know).

推荐答案

你可以调用 int nRowsEffected = database.update(...); 如果更新不影响任何行行不存在(或者你冲洗了你的 update()!)因此你需要调用 database.insert(...).当然如果 nRowsEffected > 0 那么你就完成了.

you could call int nRowsEffected = database.update(...); if there are no rows effected by the update either the row doesn't exist (or you hosed your update()!) therefore you need to call database.insert(...). of course if nRowsEffected > 0 then you are done.

这篇关于使用 database.query() 在 SQlite 和 Android 中插入或更新;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆