如何在变量中存储数据库值

时间:2014-08-08 08:53:10

标签: android sqlite

我有这个查询,我想检查它是否为null或有一些值,如果有这个值我想将它存储在变量中

max_id = db.exec(SELECT max(campaign_id)as campaign_id FROM campaign_main);

所以我想要这样的东西

if (db != null)
campaign_id = max_id + 1;
else
campaign_id = 1;

1 个答案:

答案 0 :(得分:0)

String sql = "SELECT max(campaign_id) FROM campaign_main";
long max_id = DatabaseUtils.longForQuery(db, sql, null);
if (max_id < 0)
    max_id = 0;
campaign_id = max_id + 1;

您也可以在SQL中执行逻辑:

String sql = "SELECT ifnull(max(campaign_id), 0) + 1 FROM campaign_main";
long campaign_id = DatabaseUtils.longForQuery(db, sql, null);