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)");
   }

}
4

2 回答 2

6

执行查询

DELETE FROM TABLE_NAME WHERE id = SOMEVALUE
于 2011-01-28T04:44:29.853 回答
4

看起来您正在使用这个 API,它提供了这个删除方法。我的猜测是你会这样做:

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

(原来的答案...)

使用带有 WHERE 子句的 DELETE 语句,该子句仅删除具有要删除的 id 的行:

DELETE FROM <tablename> WHERE id = ?

当然,您需要知道 id 才能执行此操作。SQLite 提供了一个函数 — sqlite3_last_insert_rowid() — 您可以在 INSERT 之后立即调用它。如果您的 API 没有直接提供此函数,您可以通过等效的SQL 函数间接获取它:

SELECT last_insert_rowid()

或者,如果您想删除某个名称(假设它是唯一的):

DELETE FROM <tablename> WHERE name = ?
于 2011-01-28T04:45:11.493 回答