我有一个Query,我试图在SQLite表上执行。表中有记录,它们映射到我传递的选择参数。以下是我的查询和全局字符串:
// Table Notifications
public static final String notificationfor = "NotificationFor";
public static final String datetonotify = "DateToNotify";
public static final String isextraordinary = "IsExtraordinary";
public static final String notificationdata = "NotificationData";
public static final String notificationdatefor= "NotificationDateFor";
public static final String primaryid= "PrimaryId";
Cursor c = mDb.rawQuery("select DateToNotify from " + DATABASE_TABLE1 +
" where " + primaryid + " = ? AND " + notificationfor + " = ?", new String[] { D, selection });
如果我将1和1作为参数传递(记录映射到我传递的参数),它会在游标中给出一个null
然而,当我执行以下查询时,它完美无缺:
String Tets = "Select DateToNotify from Notifications WHERE PrimaryId = 1 AND NotificationFor =1";
Cursor c = mDb.rawQuery(Tets, null);
修改
我刚试过以下内容并且有效:
String Tets = "Select DateToNotify from Notifications WHERE PrimaryId =" +D+ " AND NotificationFor ="+selection;
Cursor c = mDb.rawQuery(Tets, null);
整个功能如下:
public Cursor alertQueryYYYY(String D, String selection){
// Cursor c = mDb.rawQuery("select DateToNotify from " + DATABASE_TABLE1 +
// " where " + primaryid + " = ? AND " + notificationfor + " = ?", new String[] { D, selection });
String Tets = "Select DateToNotify from Notifications WHERE PrimaryId =" +D+ " AND NotificationFor ="+selection;
Cursor c = mDb.rawQuery(Tets, null);
String K = "select DateToNotify from " + DATABASE_TABLE1 +
" where " + primaryid + " = ? AND " + notificationfor + " = ?"; // new String[] { D, selection })
System.out.println("Here I am " + K);
return c;
}
修改 以下是数据库创建字符串和CL指出的错误,错误在于类型不匹配。
private static final String DATABASE_CREATE1 ="create table Notifications(_id integer primary key autoincrement, "
+"NotificationFor Integer," // Weeks/Seconds etc /7 variables
+"DateToNotify text," // Date of Notification
+"isExtraordinary Integer," // Special notifications, yet unknown
+"NotificationData Integer," // Weeks/Seconds/ etc / 7 variables
+"NotificationDateFor text,"
+"PrimaryId);";
答案 0 :(得分:1)
数字1
与字符串"1"
不同,因此如果您搜索错误类型的ID,则无法找到该记录。
查询参数有助于避免格式化问题和SQL注入攻击。 这些问题只能出现在字符串中,而不能出现在普通整数上,因此要在查询中使用整数值,不应使用参数,只需直接插入值:
"... WHERE PrimaryId =" +D+ " AND NotificationFor ="+selection;
答案 1 :(得分:0)
我更喜欢这种方式来使用查询:
final SQLiteDatabase database = getReadableDatabase();
final String[] projection = new String[] {datetonotify };
final String selection = primaryid + "=? " +notificationfor +"=?";
final String[] having = new String[] {D,selection};
Cursor cursor = database.query(DATABASE_TABLE1, projection, selection, having,
null, null, null, null);
您的代码必须工作,如果有错误,它不在参数中,但可能在变量DATABASE_TABLE1中。