当我尝试从数据库中删除记录时,我收到此错误。这是完整的错误
FATAL EXCEPTION: main
Process: itp231.dba.nyp.com.bloommain, PID: 12274
android.database.sqlite.SQLiteException: near ";": syntax error (code 1): , while compiling: DELETE FROM events WHERE id= ;
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:887)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:498)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1674)
at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1605)
at itp231.dba.nyp.com.bloommain.EventInformationPage$1.onClick(EventInformationPage.java:135)
at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:163)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
查看日志,它指示我这行代码(我的deleteRecord()方法 -
private void deleteRecord() {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setMessage("Are you sure you want delete this person?");
alertDialogBuilder.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
String id = editTextId.getText().toString().trim();
String sql = "DELETE FROM events WHERE id= " + id + ";";
db.execSQL(sql);
Toast.makeText(getApplicationContext(), "Record Deleted", Toast.LENGTH_LONG).show();
c = db.rawQuery(SELECT_SQL,null);
}
});
答案 0 :(得分:3)
1 - 您的ID是一个空字符串,因此无法在SQL命令中解析它。
2 - 如果您的id字段是TEXT(???),则需要将其括在单引号中。
3 - 对于SQL命令,使用execSQL()
代替rawQuery()
- rawQuery()
仅适用于...查询(SELECT
)
4 - 并且......准备好的语句(或绑定参数)是更好的选择。占位符(?
)将按其位置顺序自动替换,引号将不再是问题(Android将为您处理!)。
答案 1 :(得分:1)
您可以使用prepared statements
SQLiteStatement stmt = db.compileStatement("DELETE FROM events WHERE id = ?");
stmt.bindString(1, id);
stmt.execute();
答案 2 :(得分:0)
试试这个..
db.delete("events","id=?",new String[]{Integer.toString(id)});
其中,
first paramater -> will be table name from where the deletion of data need to de done.
Second parameter -> Selection field in table.based on which field we are going to perform the deletion
Third parameter -> specifies the value,to be compare it with second paramters field if it is matched,then the particular column will be deleted.
答案 3 :(得分:-1)
SQLite异常,指示SQL解析时出错 或执行。
添加此而不是您的" WHERE id= '" + id +"'";
。确保+ id +
有值,避免额外空间。
然后清理重建并卸载旧应用并再次运行。
答案 4 :(得分:-1)
您还可以使用Sugar ORM库来简化数据库操作。