简体   繁体   中英

Delete a row from sqlite database table using id

This is how I created my database

 public class MyDatabase extends SQLiteOpenHelper
 {
public static final   String DATABASE_NAME="MyDatabase.db";
public static final  int DATABASE_VERSION=1;
//table name
public static final String TABLE_NAME_INFO="info";
    //column name
public static final String ID="_id";
public static final String COL_INFO_NAME="name";
public static final String COL_INFO_GEN="gender";
// creating table


   public static final String CREATE_TABLE="create table "+TABLE_NAME_INFO+" ("+"_id INTEGER PRIMARY KEY AUTOINCREMENT,"+COL_INFO_NAME+" text,"+COL_INFO_GEN+" text)";

public MyDatabase(Context context)
{
    super(context,DATABASE_NAME,null,DATABASE_VERSION);
}


public void onCreate(SQLiteDatabase db)
{
    db.execSQL(CREATE_TABLE);
}

public void onUpgrade(SQLiteDatabase db , int oldVersion, int newVersion)
{
    db.execSQL("drop table if exists "+TABLE_NAME_INFO);
}


}

Now I want to delete a item in list view when the _id is id of the list view.Like this

  public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
 MyDatabase helper= new MyDatabase(this);
 SQLiteDatabase db=helper.getWritableDatabase();

 db.delete(MyDatabase.TABLE_NAME_INFO,MyDatabase.ID+" = "+Integer.toString((int)id), null);
  }

But it does not work . Please suggest me a way to delete the row using _id.

To delete a row from that table use the following syntax...

 db.delete(MyDatabase.TABLE_NAME_INFO, MyDatabase.ID + " = ? ",
                        new String[]{String.valueOf(id)});

It also has the benefit of prepared statements which prevents SQL injection.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM