【发布时间】:2016-05-15 17:30:45
【问题描述】:
这就是我创建数据库的方式
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 删除行的方法。
【问题讨论】:
-
无论何时单击按钮,您都会创建一个新数据库?您是否检查了 id 是否正确读取?你调试了吗?您是否添加了类似的消息:Log.v("MyApp", "Integer.toString((int)id)" 以检查数字是否正确?您已经做了什么?
-
一切正常。我的值存储在数据库中。问题是我无法使用 _id 列删除该行,尽管我使用 COL_INFO_NAME 列执行了删除并且它有效。但我想使用 _id 列删除。
-
你没有回答我的问题
-
另外,我不喜欢那里的
MyDatabase helper= new MyDatabase(this);,你不应该在点击某些东西时创建数据库,因为你每次都会创建一个新数据库。你确定你没有检查另一个数据库吗?你可以添加它来检查它是否真的在工作:int result = db.delete(MyDatabase.TABLE_NAME_INFO,MyDatabase.ID+" = "+Integer.toString((int)id), null); Log.v("TAG", result);这将打印有多少行受到影响或编辑,所以如果 Logcat 中的数字不为 0,它就工作了。 -
com.coolniks.datebase E/SQLiteLog: (1) no such column: _id 这是错误。