Android SQLite 检查是否插入了新值

11

我正在使用sqlite。我已成功创建了数据库和表。我还编写了可以向表中插入新值的代码。我的代码运行完美,但现在我想要实现:例如,如果插入了新值,则显示toast消息,否则在toast或其他地方显示错误消息。这是我的插入表源代码:

public void InsertToPhysicalPersonTable(String FirstName, String LastName,
        String FullName, String FatherName) {
    try {
        ContentValues newValues = new ContentValues();
        newValues.put("FirstName", FirstName);
        newValues.put("LastName", LastName);
        newValues.put("FullName", FullName);
        newValues.put("FatherName", FatherName);



        db.insert(AddNewPhysicalPerson, null, newValues);
    } catch (Exception e) {
        // TODO: handle exception
        e.printStackTrace();
        Toast.makeText(myContext, "Something wrong", Toast.LENGTH_SHORT).show();
    }

}

我这样调用了我的函数:

loginDataBaseAdapter.InsertToPhysicalPersonTable("FirstName",
                    "LastName",
                    "FullName",
                    "FatherName"
                    );

如果有人知道解决方案,请帮助我。 谢谢。

3个回答

36

insert()方法返回新插入行的行ID,如果发生错误,则返回-1。

db.insert(AddNewPhysicalPerson, null, newValues);

像这样

long rowInserted = db.insert(AddNewPhysicalPerson, null, newValues);
if(rowInserted != -1)
    Toast.makeText(myContext, "New row added, row id: " + rowInserted, Toast.LENGTH_SHORT).show();
else
    Toast.makeText(myContext, "Something wrong", Toast.LENGTH_SHORT).show();

我们可以在更新查询中使用相同的语句吗?它会返回更新后的行ID吗? - vishnu satheesh

4
long result = db.insert(table name, null, contentvalues);
      if(result==-1)
          return false;
           else
          return true;

这是一种适用于IT技术的好解决方案。


0

这里有另一个方法:

我不知道我是否为你的项目太晚了,但你考虑过 .lastrowid 吗?

这是我所做的示例:last_rec=self.cursor.lastrowid,因此lastrec将拥有插入的最后一行的编号。

这里是来自 sqlite.org 的信息。

希望它能帮到你或其他想了解这个的人。

亲切的问候和最好的祝愿 :¬)

joe


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接