如何用where子句删除行?

时间:2016-06-12 13:48:44

标签: android sql sqlite

我想删除行但是当我在deleteContact()中写入查询并且我的数据库执行时没有任何操作。请帮助

这是我的代码:

   public class ContactDatabase extends SQLiteOpenHelper {
        SQLiteDatabase db;
        public static final String DATABASE_NAME="totalContact.db";
        public static final  String TABLE_NAME="mecontact";
        public static final  String NAME="name";
        public static final  String PHONE="phone";


        public ContactDatabase(Context context) {
            super(context, DATABASE_NAME, null, 1);

        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            try {
                db.execSQL("create table mecontact" +
                        "(_id integer primary key autoincrement, name text, phone text)");
            }catch(android.database.SQLException e){
                    System.out.println("table create nhi ho rha");
            }
        }

    public void deleteContact(String d,int pos){
            db=this.getWritableDatabase();

            db.delete(TABLE_NAME, "name='" + d + "'"+" AND _id="+(pos), null);

            db.close();
        }

}

2 个答案:

答案 0 :(得分:0)

您只需要删除表格行的ID。

public void deleteContact(int pos){

db = this.getWritableDatabase();
db.delete(TABLE_NAME, ID_KEY + "= ?", new String[] {String.valueOf(pos) });
db.close();
}

答案 1 :(得分:0)

您可以将代码清理为:

public int deleteContact(int id) {
    db = this.getWritableDatabase();
    return db.delete(TABLE_NAME, "_id = ?", new String[]{String.valueOf(id)});       
}

public void closeDB() {
    db = this.getReadableDatabase();
    if (db != null && db.isOpen())
            db.close();
}