簡體   English   中英

如何檢查表中是否存在行?

[英]How to check if a row in a table exists?

我正在嘗試做的事情:ListView活動A,我觸摸一個項目,它會打開一個新的Listview活動。 我從列表A中選擇的數據庫行中獲取主鍵,並使用putExtra。 在活動B的onCreate中,我想檢查表B中是否有行,其中列TOPIC_CONTENT_TOPIC_ID的值等於表A中的主鍵putExtra。 如果表為空,或者沒有匹配的ID,我想創建一個新行,其中列TOPIC_CONTENT_TOPIC_ID現在等於表A中的主鍵。這是我的代碼。 它在db.query()上崩潰;

public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.topic_content);

    dbMaker = new DatabaseMaker(this);
    SQLiteDatabase db = dbMaker.getReadableDatabase();

    Intent myIntent = getIntent();
    int topicIDInt = (int) myIntent.getLongExtra("com.spentakapps.ScripturalConcordance.Topics", -1);
    String topicID = Long.toString(myIntent.getLongExtra("com.spentakapps.ScripturalConcordance.Topics", -1));

    String WHERE = DatabaseStructure.TOPICS_CONTENT_TOPIC_ID + " = " + topicID;
    Cursor cur = db.query(DatabaseStructure.TABLE_TOPICS_CONTENT, new String[] {DatabaseStructure.TOPICS_CONTENT_CONTENT},WHERE, null, null, null, null);

    if (cur.getCount() <= 0)
    {
        ContentValues values = new ContentValues();
        values.put(DatabaseStructure.TOPICS_CONTENT_TOPIC_ID, topicIDInt);
        db = dbMaker.getWritableDatabase();
        db.insert(DatabaseStructure.TABLE_TOPICS_CONTENT, null, values);
        db = dbMaker.getReadableDatabase();
        cur = db.query(DatabaseStructure.TABLE_TOPICS_CONTENT, new String[] {DatabaseStructure.TOPICS_CONTENT_TOPIC_ID},WHERE, null, null, null, null);
    }

    View addContentButton = findViewById(R.id.content_button_add);
    addContentButton.setOnClickListener(this);

    //Set up data binding
    SimpleCursorAdapter  adapter = new SimpleCursorAdapter(this,R.layout.topiccontentlineitem,cur, FROM,TO);
    setListAdapter(adapter);

}

對於這些問題,我的建議始終是使用以下方法登錄仿真器:

adb shell

然后直接打開sqlite數據庫

# cd /data/data/<your application package>/databases/
# ls
# sqlite3 <your database file>

一旦進入內部,您應該可以嘗試手動運行sql以確保其有效:

select id from TABLE_TOPICS_CONTENT where id='someidvalue' limit 1

當您說它在db.query上崩潰時,上述代碼中有兩個db.query狀態菜單。 我的猜測是,由於您正在調用dbMaker.getReadableDatabase();您遇到了重大問題dbMaker.getReadableDatabase(); 幾次。 嘗試僅在開始時就以可運行的方式對其進行調用,並嘗試使用它們來驗證您的sql是否有效。 如果失敗,請附加錯誤日志。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM