我收到错误" SQLiteLog:(1)接近"?":语法错误" ,任何人都知道我的错误是什么码?我已经尝试尝试试错,以解决这个问题,但仍然没有结果..
这里是错误日志的标题:
E/SQLiteLog: (1) near "?": syntax error
E/AndroidRuntime: FATAL EXCEPTION: IntentService[SyncVideoServices]
Process: com.sbi.mvicall, PID: 11872
android.database.sqlite.SQLiteException: near "?": syntax
error (code 1): , while compiling: SELECT _id, caller_id, name, msisdn, pic,
status, video, profiles FROM tbl_caller WHERE msisdn IN (?
这是我的java代码:
public String [] getRegisteredMSISDN(String [] msisdn){
if(msisdn != null && msisdn.length > 0){
String whereStatement = "";
for(int i=0; i<msisdn.length; i++){
whereStatement += ",";
if(i==0){
whereStatement += "(?";
}
else if(i==msisdn.length-1){
whereStatement += "?)";
}
else{
whereStatement += "?";
}
}
whereStatement = whereStatement.substring(1);
whereStatement = UserTable.UserEntry.COLUMN_NAME_MSISDN + " IN " + whereStatement;
SQLiteDatabase database = DBHelper
.getInstance(applicationContext)
.getReadableDatabase();
// =============== The error pointing code below ==============
Cursor cursor = database.query(UserTable.UserEntry.TABLE_NAME, UserTable.ALL_COLUMNS, whereStatement, msisdn,
null,
null,
null);
String [] result = null;
if (cursor.getCount() > 0) {
int index = 0;
result = new String[cursor.getCount()];
while (cursor.moveToNext()) {
result[index] = cursor.getString(cursor.getColumnIndex(UserTable.UserEntry.COLUMN_NAME_MSISDN));
index++;
}
}
cursor.close();
return result;
}
return null;
}
答案 0 :(得分:1)
检查if..else
声明,以构建whereStatement
。如果您的msisdn
只有1个元素,则(?
中会显示whereStatement
。
不要将(
添加到第一个,)
添加到最后,只需在周期前添加(
,在周期后添加)
。此外,您只需在whereStatement.length > 0
答案 1 :(得分:1)
使用以下内容: -
String whereStatement = "";
for(int i=0; i<msisdn.length; i++){
whereStatement += ",";
if(i==0){
whereStatement += "(?";
}
else if(i==msisdn.length-1){
whereStatement += "?)";
}
else{
whereStatement += "?";
}
}
如果msisdn有1个值,那么
else
将被跳过,因此for循环的下一次迭代开始, i 设置为 1 。我相信以下内容可以满足您的需求,作为上述代码的替代品: -
whereStatement = "("; // Add opening parenthesis
for (int i = 0; i < msisdn.length; i++) {
if (i > 0) {
whereStatement += ","; // add a comma separator if not the first arg
}
whereStatement += "?"; // add the placement ? (for every arg)
}
whereStatement += ")"; // finally add the closing parenthesis
以下用于测试: -
for (int i=0; i < 10; i++) {
String[] msisdn = new String[i+1];
for (int j=0; j < msisdn.length; j++) {
msisdn[j] = "Test" + String.valueOf(j);
}
buildWhereStatement(msisdn);
}
使用buildWhereStatement
方法: -
public void buildWhereStatement(String[] msisdn) {
String whereStatement = "";
if (msisdn != null && msisdn.length > 0) {
whereStatement = "(";
for (int i = 0; i < msisdn.length; i++) {
if (i > 0) {
whereStatement += ",";
}
whereStatement += "?";
}
whereStatement += ")";
}
Log.d("WHERESTMNT",whereStatement);
}
04-06 10:08:22.064 1367-1367/? D/WHERESTMNT: (?)
(?,?)
(?,?,?)
(?,?,?,?)
(?,?,?,?,?)
(?,?,?,?,?,?)
(?,?,?,?,?,?,?)
(?,?,?,?,?,?,?,?)
(?,?,?,?,?,?,?,?,?)
(?,?,?,?,?,?,?,?,?,?)