我想检查SQLite数据库表记录。表行是否存在然后更新或删除我的表行或。当我运行我的应用程序时,表行插入副本。如何避免它。我想在第一次运行时插入新记录,当我的数据库第二次更新时打开活动。我试过但db没有显示那里的记录。请帮助我。谢谢赞赏
这是我的代码
public boolean Exists(String _id)
{
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery("select Company_Id from Company where Company_Id = ?",
new String[]{_id});
boolean exists = (cursor.getCount() > 0);
cursor.close();
return exists;
}
我的片段代码
if(jsonStr != null)
try {
JSONObject jsonObj = new JSONObject(jsonStr);
String jsonResult = jsonObj.toString().trim();
Log.e("jsonResult ", " = " + jsonResult);
JSONObject companyList = jsonObj.getJSONObject("Get_CompanyResult");
Log.e("companyList ", " = " + companyList.toString());
JSONArray jarr = companyList.getJSONArray("CompanylList");
Log.e("jarr ", " = " + jarr.toString());
for (int i = 0; i < jarr.length(); i++) {
JSONObject jobCompanyDetails = jarr.getJSONObject(i);
str_CompanyId = jobCompanyDetails.getString("Company_ID");
str_CompanyName = jobCompanyDetails.getString("Company_Name");
Log.e("str_CompanyId ", " = " + str_CompanyId);
Log.e("str_CompanyName ", " = " + str_CompanyName);
if(dbhelper.Exists(str_CompanyId))
{
Log.e("Row is Already ","Exist");
}
else
{
dbhelper.insertCompany(str_CompanyId, str_CompanyName);
Log.e("Data insert into ", " Company Table Succesively !!! = ");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
答案 0 :(得分:1)
使用以下方法
public boolean isIDExist(String _id){
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(Company, new String[] { KEY_your_id}, KEY_your_id + "=?" ,
new String[] { String.valueOf( _id)}, null, null, null, null);
if (cursor != null){
if(cursor.getCount() == 0){
cursor.close();
db.close();
return false;
}else{
cursor.close();
db.close();
return true;
}
}
return false;
}
答案 1 :(得分:-1)
将您的代码更改为此
public boolean Exists(String _id)
{
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery("select Company_Id from Company where Company_Id ='"+ String _id + "'", null);
boolean exists = (cursor.getCount() > 0);
cursor.close();
return true;
}
答案 2 :(得分:-1)
我认为最简单的方法是在表中创建一个主键,然后使用INSERT OR REPLACE命令而不是仅使用INSERT。 INSERT或REPLACE将在遇到主键违规时自动替换现有行,并插入新数据。
在这种情况下,您可以将OrgId作为主键,如果您有一些记录,如:
ORGID ORGNAME
1 ABC
你插入像INSERT OR REPLACE INTO ORG_MASTER(1,'EFG'),表格现在会有一行像
ORGID ORGNAME
1 EFG
希望这会有所帮助:)