如何使用sqlite在java中创建条件

如何使用sqlite在java中创建条件,java,android,sqlite,Java,Android,Sqlite,我想做一个条件,如果名字和姓氏在数据库中,分数将被更新,否则数据将作为新用户正常插入 我的代码: public void data(View view) { scor=String.valueOf(qc1.scor); db.execSQL("UPDATE Student SET email='"+scor+"' WHERE fname ='"+exo.fname+"' AND lname ='"+exo.lname+"';"); Toast toast = Toa

我想做一个条件,如果名字和姓氏在数据库中,分数将被更新,否则数据将作为新用户正常插入

我的代码:

public void data(View view)
{  
    scor=String.valueOf(qc1.scor);
    db.execSQL("UPDATE Student SET email='"+scor+"' WHERE fname ='"+exo.fname+"' AND lname ='"+exo.lname+"';");
     Toast toast = Toast.makeText(getApplicationContext(), "data updated", Toast.LENGTH_LONG);
     toast.show();
}

像这样的事情应该可以做到:

    Cursor cursor = db.rawQuery("select 1 from Student where fname=? AND lname =?", 
         new String[] { exo.fname, exo.lname });
    if(cursor.getCount() > 0) {
        // this means we found at least one entry that matches the name
        // update database here
    } else {
        // otherwise that user doesn't exist yet
        // insert into database here
    }
这可能对你有帮助

  ContentValues cv = new ContentValues();
  cv.put(columnName,columnValue);
  long x = sqLiteDatabase.update(TableName,cv,columnName1 " = ? and "+columnName2+" = ? ",new String[]{coulmn1Val,column2val});
  if(x<=0){

    // insert data because no any record is updated 
    //insert statement here
  }
ContentValues cv=new ContentValues();
cv.put(columnName、columnValue);
长x=sqLiteDatabase.update(TableName,cv,columnName1“=?和“+columnName2+”=?”,新字符串[]{coulmn1Val,column2val});
if(x如果具有唯一约束,则可以与conflictAlgorithm一起使用

当发生唯一约束冲突时…插入或更新总是发生


您可以通过几种不同的方式解决此问题:

  • 检查行是否存在(使用
    query()
    )。如果存在,则插入,否则更新
  • 尝试更新。如果未更新任何记录,请插入
  • 我建议使用方法2,因为它可以为您节省一次语句执行(特别是在更新很常见的情况下)。例如:

    ContentValues values = new ContentValues();
    values.put("email", scor);
    if (db.update("Student", values, "fname = ? AND lname = ?", new String[] { exo.fname, exo.lname }) == 0)
    {
        // Not an update. Insert
        values.put("fname", exo.fname);
        values.put("lname", exo.lname);
        db.insert("Student", null, values);
    }
    

    你现在得到了什么输出?如果fname和lname是主键(或者有一个唯一的约束),这可能是最好的解决方案。谢谢,伙计,它真的有效,但我不知道为什么它以前不起作用。你是最好的,我不知道你能做到这一点,谢谢兄弟,这将对我有很大帮助