如果存在其他插入的记录,如何更新sqlite表?

时间:2016-02-10 03:46:58

标签: android sqlite

这可能是重复的问题,但我很困惑,因为我是新的sql和android我得到服务器的响应需要保存在sqlite db如果表中的值已经存在更新其他插入il检查与任务ID,这是唯一的'我知道如何做到这一点,我已经搜索并做了很多模式,但没有一个工作,请你帮助我!让我发布我的代码:

这是模型类:

import java.io.Serializable;

/**
 * Created by 4264 on 02-02-2016.
 */
public class Model_Task_List implements Serializable {


    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public int id;
    public String UserName;
    public String Subject;
    public String TaskStatus;

    public int getTaskID() {
        return TaskID;
    }

    public void setTaskID(int taskID) {
        TaskID = taskID;
    }

    public int TaskID;
    public static String KEY_table="task";
    public  static String KEY_id="id";
    public  static String KEY_username="name";
    public  static String KEY_subject="subject";
    public  static String KEY_task="status";
    public static String KEY_taskid="taskid";
    public static String KEY_owner="owner";

    public String getUserid() {
        return userid;
    }

    public void setUserid(String userid) {
        this.userid = userid;
    }

    public String userid;

    public String getSubject() {
        return Subject;
    }

    public void setSubject(String subject) {
        Subject = subject;
    }

    public String getTaskStatus() {
        return TaskStatus;
    }

    public void setTaskStatus(String taskStatus) {
        TaskStatus = taskStatus;
    }

    public String getUserName() {
        return UserName;
    }

    public void setUserName(String userName) {
        UserName = userName;
    }

    public Model_Task_List(String subject, String taskStatus, String userName) {
        Subject = subject;
        TaskStatus = taskStatus;
        UserName = userName;
    }
    public Model_Task_List(){

    }
}

这是我的数据库查询:

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import java.util.ArrayList;
import java.util.List;


    public class Database_SF_APP  extends SQLiteOpenHelper {
    Context context;
    private static final int DATABASE_VERSION = 4;
    private static final String DATABASE_NAME = "crud.db";

    public Database_SF_APP(Context context ) {

        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String CREATE_TABLE_TASK = "CREATE TABLE " + Model_Task_List.KEY_table  + "("
                + Model_Task_List.KEY_id  + " INTEGER PRIMARY KEY AUTOINCREMENT ,"
                + Model_Task_List.KEY_username + " TEXT, "
                + Model_Task_List.KEY_subject + " TEXT, "
                + Model_Task_List.KEY_task + " TEXT, "
                +Model_Task_List.KEY_taskid+ " INTEGER, "
                +Model_Task_List.KEY_owner+ " TEXT"
                + ");";

        db.execSQL(CREATE_TABLE_TASK);

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + Model_Task_List.KEY_table);
        onCreate(db);

    }


    public void insert(Model_Task_List modelobj) {

        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(Model_Task_List.KEY_username, modelobj.getUserName());
        values.put(Model_Task_List.KEY_subject,modelobj.getSubject());
        values.put(Model_Task_List.KEY_task, modelobj.getTaskStatus());
        values.put(Model_Task_List.KEY_taskid,modelobj.getTaskID());
        values.put(Model_Task_List.KEY_owner,modelobj.getUserid());
        db.insert(Model_Task_List.KEY_table, null, values);
        db.close();

        }

        public List<Model_Task_List> getTaskListById(String id) {
            SQLiteDatabase db = this.getReadableDatabase();
            String selectQuery =  " SELECT  " +
                    Model_Task_List.KEY_id + "," +
                    Model_Task_List.KEY_username + "," +
                    Model_Task_List.KEY_subject + "," +
                    Model_Task_List.KEY_task + "," +
                    Model_Task_List.KEY_taskid  + ","+
                    Model_Task_List.KEY_owner +
                    " FROM " + Model_Task_List.KEY_table + " WHERE "   +  Model_Task_List.KEY_owner + "= " + id +"";
            List<Model_Task_List>listobj=new ArrayList<Model_Task_List>();
            Cursor cursor = db.rawQuery(selectQuery, null);
            if (cursor.moveToFirst()) {
                while (cursor.moveToNext()) {
                    Model_Task_List modelobj=new Model_Task_List();
                    modelobj.setId(Integer.parseInt(cursor.getString(0)));
                    modelobj.setUserName(cursor.getString(1));
                    modelobj.setSubject(cursor.getString(2));
                    modelobj.setTaskStatus(cursor.getString(3));
                    modelobj.setTaskID(cursor.getShort(4));
                    modelobj.setUserid(cursor.getString(5));
                    listobj.add(modelobj);

                }
            }
            return listobj;

        }


    public List<Model_Task_List> getTaskList() {
        Model_Task_List model_task_list=new Model_Task_List();
        SQLiteDatabase db = this.getReadableDatabase();
        String selectQuery =  "SELECT  " +
                Model_Task_List.KEY_id + "," +
                Model_Task_List.KEY_username + "," +
                Model_Task_List.KEY_subject + "," +
                Model_Task_List.KEY_task +"," +
                Model_Task_List.KEY_taskid  +
                " FROM " + Model_Task_List.KEY_table;
            List<Model_Task_List>listobj=new ArrayList<Model_Task_List>();
            Cursor cursor = db.rawQuery(selectQuery, null);
            if (cursor.moveToFirst()) {
            while (cursor.moveToNext()) {
                Model_Task_List modelobj=new Model_Task_List();
                modelobj.setId(Integer.parseInt(cursor.getString(0)));
                modelobj.setUserName(cursor.getString(1));
                modelobj.setSubject(cursor.getString(2));
                modelobj.setTaskStatus(cursor.getString(3));
                modelobj.setTaskID(cursor.getShort(4));
                listobj.add(modelobj);

            }
        }
        return listobj;

    }
    public int getTaskCount() {
        int count=0;
        String countQuery = "SELECT  * FROM " + Model_Task_List.KEY_table;
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(countQuery, null);
        if(cursor != null && !cursor.isClosed()){
            count = cursor.getCount();
            cursor.close();
        }
        return count;

    }
    public void update(Model_Task_List student) {

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

        values.put(Model_Task_List.KEY_username, student.getUserName());
        values.put(Model_Task_List.KEY_subject,student.getSubject());
        values.put(Model_Task_List.KEY_task, student.getTaskStatus());
        values.put(Model_Task_List.KEY_taskid,student.getTaskID());
        db.update(Model_Task_List.KEY_table, values, Model_Task_List.KEY_taskid + "= ?", new String[]{String.valueOf(student.getTaskID())});
        db.close();
    }

    }

以下是需要检查更新或插入位置的代码:

import android.content.Context;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by 4264 on 27-01-2016.
 */
public class Task extends Fragment  {
    private static final String MY_PREFERENCE_KEY = "yogan";
    private List<Model_Task_List> model_task_lists;

    //Creating Views
    String currentDateTimeString;
    Context context;
    SharedPreferences.Editor editor;
    private RecyclerView recyclerView;
    Task_List_Adapter taskadapter;
    private RecyclerView.LayoutManager layoutManager;
    SharedPreferences sharedPreferences;
    private RecyclerView.Adapter adapter;
    RequestQueue yog;
    String user_id;
    AppController app;
    RequestQueue queue;
    String Url;
    Task_DB task_db = null;
    Database_SF_APP database_sf_app;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_task, container, false);
        recyclerView = (RecyclerView) view.findViewById(R.id.my_recycler_view);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setLayoutManager(layoutManager);
        if (model_task_lists == null) {
            model_task_lists = new ArrayList<Model_Task_List>();
        }
        database_sf_app = new Database_SF_APP(getActivity().getBaseContext());
        int count=database_sf_app.getTaskCount();
        sharedPreferences = getActivity().getSharedPreferences(LoginActivity.login, 0);
        user_id = sharedPreferences.getString("user_id", null);
        queue = Volley.newRequestQueue(getContext());
        String date="2016-02-09T19:59:27.9434387+05:30";
        Url = "http://xxx.xx.x.xx/xxx/GetActivitiesByUserID.svc/getlist/getTask/" + user_id ;
        ConnectivityManager cn = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo nf = cn.getActiveNetworkInfo();
        if (nf != null && nf.isConnected()) {
            Toast.makeText(getActivity(), "Network Available", Toast.LENGTH_LONG).show();
            JsonObjectRequest jsonObjRequest = new JsonObjectRequest(Request.Method.GET, Url, new JSONObject(),
                    new Response.Listener<JSONObject>() {

                        @Override
                        public void onResponse(JSONObject response) {
                            String server_response = response.toString();
                            try {
                                JSONObject json_object = new JSONObject(server_response);
                                JSONArray json_array = new JSONArray(json_object.getString("GetTaskResult"));
                                for (int i = 0; i < json_array.length(); i++) {
                                    Model_Task_List modelobj = new Model_Task_List();
                                    JSONObject json_arrayJSONObject = json_array.getJSONObject(i);
                                    modelobj.setSubject(json_arrayJSONObject.getString("Subject"));
                                    modelobj.setTaskID(json_arrayJSONObject.getInt("TaskID"));

                                    modelobj.setUserName(json_arrayJSONObject.getString("DueDate"));
                                    modelobj.setTaskStatus(json_arrayJSONObject.getString("TaskStatus"));
                                    modelobj.setUserid(json_arrayJSONObject.getString("Owner"));
                                    model_task_lists.add(modelobj);
                                  ///Here i need to check 

                                    database_sf_app.update(modelobj);
                                    taskadapter = new Task_List_Adapter(model_task_lists, getContext());
                                    recyclerView.setAdapter(taskadapter);
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                        }
                    },
                    new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            Toast.makeText(getContext(), error.toString(), Toast.LENGTH_SHORT).show();
                            Log.e("error", error.toString());
                        }
                    });

            //Creating request queue

            queue.add(jsonObjRequest);

        }

        //sync operation
        //a union b
        //a server
        //b local storage

        //a only - insert local
        //b only - send to server
        //a = b do nothing

        //result
        //bind

        model_task_lists=database_sf_app.getTaskListById(user_id);
        Log.e("Test",model_task_lists.toString());
        taskadapter=new Task_List_Adapter(model_task_lists,getActivity());
        recyclerView.setAdapter(taskadapter);

        return view;
    }


    @Override
    public void onResume()
    {
            super.onResume();
    }


    @Override
    public void onStop() {

        super.onStop();
    }

}

喜欢这样,如果是更新或插入,则检查表中是否已存在任何任务ID:

public void insertOrUpdate(Model_Task_List modelobj)
{
            String query=" SELECT  * FROM " + Model_Task_List.KEY_table+ " WHERE" +Model_Task_List.KEY_taskid+  " =" +modelobj.getTaskID();
            SQLiteDatabase db=this.getReadableDatabase();
            ContentValues values=new ContentValues();
            Cursor cursor=db.rawQuery(query, null);
            if(cursor.moveToFirst()){
                update(modelobj);
            }
             else
            {
                insert(modelobj);
            }
}

3 个答案:

答案 0 :(得分:1)

update()函数返回受影响的行数。 因此,如果没有,您知道必须插入:

void updateIfExistsElseInsert(...) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues values = ...;
    values.put( /* all except the ID */ );
    int rows = db.update(KEY_TABLE, values, KEY_ID + " = " + id, null);
    if (rows == 0) {
        values.put(KEY_ID, id);
        db.insert(KEY_TABLE, null, values);
    }
}

答案 1 :(得分:0)

你必须检查它是否存在。就像这段代码一样:

 private Cursor selectOneItem(int id) {
    String strQuery = String.format(
            "SELECT * FROM %s WHERE %s = %s", Model_Task_List.KEY_table,
            Model_Task_List.KEY_id, id);
    Cursor cur = db.rawQuery(strQuery , null);
    return cur;
}

将上面的代码用于您的插入函数,如下所示:

 public void insert(Model_Task_List modelobj) {
         Cursor cur = selectOneNews(modelobj.getTaskID());
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(Model_Task_List.KEY_username, modelobj.getUserName());
        values.put(Model_Task_List.KEY_subject,modelobj.getSubject());
        values.put(Model_Task_List.KEY_task, modelobj.getTaskStatus());
        values.put(Model_Task_List.KEY_taskid,modelobj.getTaskID());
        values.put(Model_Task_List.KEY_owner,modelobj.getUserid());
        if (cur == null || cur.getCount() == 0) {
                    db.insert(Model_Task_List.KEY_table, null, values);
                } else {
                    String[] args = {modelobj.getTaskID() + ""};
                    db.update(Model_Task_List.KEY_table, values,
                            Model_Task_List.KEY_id + "=?", args);
                }
        db.close();

    }

答案 2 :(得分:-1)

replace就像insert一样,它只是检查是否有重复的键,如果它是删除行,并插入新的,否则只是插入

如果存在(Model_Task_List.KEY_taskid)的唯一索引并且键入以下命令,则可以执行此操作

REPLACE INTO Model_Task_List.KEY_table(Model_Task_List.KEY_taskid,Model_Task_List.KEY_task,Model_Task_List.KEY_username,Model_Task_List.KEY_subject) VALUES ('111',3,50,90 )

并且已存在一行Model_Task_List.KEY_taskid ='111'它将被替换

CREATE UNIQUE INDEX idx_name_type ON Model_Task_List.KEY_table(Model_Task_List.KEY_taskid)
编辑:快速注释 - REPLACE总是DELETES然后INSERT,因此在重负载中使用它永远不是一个好主意,因为它在删除时需要独占锁定,然后在插入时

某些数据库引擎

INSERT ... ON DUPLICATE KEY UPDATE ...

Link