我想在我的应用中创建一个删除功能,以删除超过一天前添加的行和一个值为“C”的列。我遇到问题如何将当前系统日期与存储在数据库列中的日期进行比较,
public int RemoveSyncData(){
DBHelper = new DatabaseHelper(context);
DateFormat dateFormat = new SimpleDateFormat("MM-dd-yyyy hh:mm:ss a");
Calendar calObj = Calendar.getInstance();
String currentDate = dateFormat.format(calObj.getTime());
Log.e("current date",currentDate);
int totalRows = db.delete(DATABASE_TABLE_ATTENDANCE,SYN_STATUS + "= ? and " + CREATED_DATE + " < " + currentDate, new String[] {"C,"});
db.close();
return totalRows;
}
我使用相同的日期格式进行比较,bleow是我的Logcat
07-24 10:50:37.018: E/AndroidRuntime(21580): Caused by: android.database.sqlite.SQLiteException: near "10": syntax error (code 1): , while compiling: DELETE FROM dailyattendance WHERE sync_status= ? and created_date < 07-24-2015 10:50:36 AM
07-24 10:50:37.018: E/AndroidRuntime(21580): at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
07-24 10:50:37.018: E/AndroidRuntime(21580): at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:882)
07-24 10:50:37.018: E/AndroidRuntime(21580): at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:493)
07-24 10:50:37.018: E/AndroidRuntime(21580): at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
答案 0 :(得分:1)
以下代码中的更正应该会有所帮助。我们需要使用单引号来包含值
int totalRows = db.delete(DATABASE_TABLE_ATTENDANCE, SYN_STATUS + "= ? and " + CREATED_DATE + " < '" + currentDate + "'", new String[] {"C"});
此外,您可以使用SQLite的DATE_TIME函数将字符串转换为日期时间以进行匹配。这是一种可以重写代码的方法。请注意SimpleDateFormat
格式的更改,并更改为查询。
public int RemoveSyncData(){
DBHelper db = new DatabaseHelper(context);
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Calendar calObj = Calendar.getInstance();
String currentDate = dateFormat.format(calObj.getTime());
Log.e("current date",currentDate);
int totalRows = db.delete(DATABASE_TABLE_ATTENDANCE,SYN_STATUS + "= ? and " + CREATED_DATE + " < DATE_TIME(?)", new String[] {"C", currentDate});
db.close();
return totalRows;
}
我没有对上面的代码进行过测试,但它应该提出这个想法。