2011-01-28 155 views
0

我有刪除只有一行的問題。我可以插入和刪除整個表。我無法理解整個ID的事情,以便刪除一行,我正在看一些例子,我無法得到它。它讓我瘋狂,任何幫助都會非常感激。 這是sqlite類;從數據庫中刪除一行

public class datahelper { 
    private static final String DATABASE_NAME = "table.db"; 
    private static final int DATABASE_VERSION = 1; 
    private static final String TABLE_NAME = "table1"; 

    private Context context; 
    private SQLiteDatabase db; 
    private SQLiteStatement insertStmt; 

    private static final String INSERT = 
     "insert into " + TABLE_NAME + "(name) values (?)"; 

    public datahelper(Context context) { 
     this.context = context; 
     OpenHelper openHelper = new OpenHelper(this.context); 
     this.db = openHelper.getWritableDatabase(); 
     this.insertStmt = this.db.compileStatement(INSERT); 
    } 

    public long insert(String name) { 
     this.insertStmt.bindString(1, name); 
     return this.insertStmt.executeInsert(); 
    } 

    public long insert2(String name) { 
      this.insertStmt2.bindString(1, name); 
      return this.insertStmt2.executeInsert(); 
    } 

    public void deleteAll() { 
     this.db.delete(TABLE_NAME, null, null); 
    } 

    private static class OpenHelper extends SQLiteOpenHelper { 
     OpenHelper(Context context) { 
     super(context, DATABASE_NAME, null, DATABASE_VERSION); 
     } 

     @Override 
     public void onCreate(SQLiteDatabase db) { 
     db.execSQL("CREATE TABLE " + TABLE_NAME + 
        " (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)"); 
    } 
} 

回答

5

執行查詢

DELETE FROM TABLE_NAME WHERE id = SOMEVALUE 
4

編輯:基於您的反饋,它看起來像你正在使用this API,它提供this delete method。我的猜測是,你可以這樣做:

public void delete(int id) { 
    this.db.delete(TABLE_NAME, 'id = ?', new String[] { id.toString() }); 
} 

(原來的答覆...)

使用與你要刪除的ID只刪除該行WHERE子句DELETE語句:

DELETE FROM <tablename> WHERE id = ? 

當然,你需要知道id爲了做到這一點。 SQLite提供了一個函數 - sqlite3_last_insert_rowid() - 您可以在INSERT後立即調用。如果你的API不直接提供此功能,您可以通過相當於SQL function得到它間接:

SELECT last_insert_rowid() 

Alernatively如果你想刪除某個名字(假設它是唯一的):

DELETE FROM <tablename> WHERE name = ? 
+0

什麼令我困惑的是,我不能只輸入該代碼,我認爲它必須看起來像這樣public void delete(String id) { \t this.db.delete(TABLE_NUM,「id =?」,null); } – 2011-01-28 05:40:40