我想知道如何验证以检查是否存在“数据库column1”,然后输入和保存任何内容。它将变为“更新”,而不是创建新的“ Column2”。
这是代码
sB_Save.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SettingModel txn = new SettingModel(); // initialize your model class first
txn.setH1(h1.getText().toString());
txn.setH2(h2.getText().toString());
txn.setH3(h3.getText().toString());
txn.setH4(h4.getText().toString());
txn.setPerson_Charge(Person_Charge.getText().toString());
txn.setUnit_Code(unit_Code.getText().toString());
try {
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("header1", txn.getH1()); // get the entered name here.
cv.put("header2", txn.getH2());
cv.put("header3", txn.getH3());
cv.put("header4", txn.getH4());
cv.put("unitcode", txn.getUnit_Code());
cv.put("personInCharge", txn.getPerson_Charge());
db.insert("Information", null, cv);
db.close();
Toast.makeText(Setting_Page.this, "Add successfully", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
它需要'if statement',但是我不知道该如何验证...请帮助。预先感谢
答案 0 :(得分:1)
您可以使用以下内容。
public void onClick(View v) {
SettingModel txn = new SettingModel(); // initialize your model class first
txn.setH1(h1.getText().toString());
txn.setH2(h2.getText().toString());
txn.setH3(h3.getText().toString());
txn.setH4(h4.getText().toString());
txn.setPerson_Charge(Person_Charge.getText().toString());
txn.setUnit_Code(unit_Code.getText().toString());
SQLiteDatabase db = dbHelper.getWritableDatabase();
Cursor csr = db.query("Information",null,null,null,null,null,null);
int rowcount = csr.getCount();
csr.close();
ContentValues cv = new ContentValues();
cv.put("header1", txn.getH1()); // get the entered name here.
cv.put("header2", txn.getH2());
cv.put("header3", txn.getH3());
cv.put("header4", txn.getH4());
cv.put("unitcode", txn.getUnit_Code());
cv.put("personInCharge", txn.getPerson_Charge());
if (rowcount == 0) {
db.insert("Information", null, cv);
Toast.makeText(Setting_Page.this, "Add successfully", Toast.LENGTH_SHORT).show();
} else {
db.update("Information",cv,null,null);
Toast.makeText(Setting_Page.this, "Updated successfully", Toast.LENGTH_SHORT).show();
}
db.close();
}
另一种方法(也许有人会说正确的方法)是在一个或多个列上创建UNIQUE(索引)约束,然后将 insertWithonConflict
与 CONFLICT_REPLACE (与SQL INSERT OR REPLACE .......
等效)。