使用id从sqlite数据库表中删除一行

时间:2016-05-15 17:30:46

标签: java android mysql sqlite

这是我创建数据库的方式

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


}

现在我想在_id是列表视图的id时删除列表视图中的项目。就像这个

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

但它不起作用。请建议我使用_id删除行的方法。

1 个答案:

答案 0 :(得分:-1)

要从该表中删除行,请使用以下语法...

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

它还具有防止SQL注入的预准备语句的好处。