android sqlite检查是否插入新值

chr*_*end 9 t-sql database sqlite android

我正在使用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();
    }

}
Run Code Online (Sandbox Code Playgroud)

我这样调用我的函数:

loginDataBaseAdapter.InsertToPhysicalPersonTable("FirstName",
                    "LastName",
                    "FullName",
                    "FatherName"
                    );
Run Code Online (Sandbox Code Playgroud)

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

Roh*_*5k2 33

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

更改

db.insert(AddNewPhysicalPerson, null, newValues);
Run Code Online (Sandbox Code Playgroud)

像这样

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();
Run Code Online (Sandbox Code Playgroud)