2016-06-13 84 views
0

这是我的创建函数,它将数组数据插入到数据库中.Data从服务器中获取并在db中插入。如何在sqlite中插入检查项是否存在,如果存在则更新它,如果不存在,则插入

public long createEmployee_New(ArrayList<Customer> aCustomer) { 

     long row_id = 0; 
     SQLiteDatabase db = this.getWritableDatabase(); 
     ContentValues values = new ContentValues(); 

     for(int i = 0;i<aCustomer.size();i++) { 

      Customer employee = new Customer(); 
      employee = aCustomer.get(i); 
      values.put(EMP_ID, employee.getEmpID()); 
      values.put(EMP_TYPE, employee.getEmpType()); 
      values.put(EMP_CITY, employee.getEmpCity()); 
      values.put(EMP_NAME, employee.getEmpName()); 
      values.put(EMP_CONTACT_PERSON, employee.getEmpContactPersonName()); 
      values.put(EMP_CONTACT, employee.getEmpContactNo()); 
      values.put(EMP_ADD, employee.getEmpAddress()); 
      values.put(EMP_STATE, employee.getEmpState()); 
      values.put(EMP_DELSTATE, employee.getEmpDelState()); 
      values.put(CUSTOMER_LANDLINE, employee.getCustomer_landline()); 
      values.put(CUST_COMPANY_ID, employee.getCust_companyID()); 
      values.put(CUSTOMER_EMAIL_ID,employee.getCust_emailID()); 
      values.put(PRICE_LIST_ID_FK,employee.getPRICE_LIST_ID_FK()); 

      row_id = db.insert(TABLE_EMPLOYEE, null, values); 
     } 

     db.close(); 
     return row_id; 
    } 

我怎么能检查是否EMPID这是唯一的出口在表,如果存在,则更新该特定EMPID,如果它不是在数据库目前的数据,然后创建

回答

1

更新和插入数据,您还可以使用下面的方法

mDatabase.insertWithOnConflict(TABLE_EMPLOYEE, null, values, 
       SQLiteDatabase.CONFLICT_REPLACE); 
+0

thanq v much .. :) –

+0

永远wlc @PrachiKarapurkar –

+0

我有5000多名员工。在db中插入它们的最好方法是什么? –

0
Cursor cursor = null; 
String idValue="5"; //the employee id which you want to insert 
String sql ="SELECT EMP_ID FROM "+TableName+" WHERE EMP_ID="+ idValue; 
cursor= db.rawQuery(sql,null); 
Log("Cursor Count : " + cursor.getCount()); 

if(cursor.getCount()>0){ 
    // employee ID Found put update query here 
}else{ 
//employee ID Not Found put insert query here 
} 
+0

这将是idValue?我通过arraylist –

+0

你想插入的员工ID –

+0

thanq v much .. :) –

0

您可以使用替换成 命令而不是插入命令。 它适用于MySQL。

+0

thanq v much .. :) –

+0

我有5000 +加雇员。在db中插入它们的最好方法是什么? –

+0

mysql有批量插入语法,可以使用一个插入命令插入5000条记录。我怀疑其他DBMS可以做到这一点。但是在其他DBMS中,您可以在插入一千个记录后提交更改以加快操作速度。 –

1

您可以使用该方法insertWithOnConflictCONFLICT_REPLACE不变样,

db.insertWithOnConflict(TABLE_EMPLOYEE, null, values, SQLiteDatabase.CONFLICT_REPLACE); 
相关问题