WHERE子句不适用于SQLite

时间:2018-06-18 06:59:22

标签: java android sqlite android-sqlite

我目前正在使用SQLite数据库进行Android应用程序,我想创建一个方法来检索与一个所有者关联的所有任务,但是应用程序无法检索它们,而是返回一个异常。我该如何解决这个问题?

这是数据库的代码:

public class SchedulerDbHelper extends SQLiteOpenHelper {

public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "scheduler.db";
public static final String TABLE_NAME = "SCHEDULER_TABLE";
public static final String TASK_NAME = "NAME";
public static final String TASK_YEAR = "YEAR";
public static final String TASK_MONTH = "MONTH";
public static final String TASK_DAY = "DAY";
public static final String TASK_HOUR = "HOUR";
public static final String TASK_MINUTE = "MINUTE";
public static final String TASK_DESCRIPTION = "DESCRIPTION";
public static final String TASK_OWNER = "OWNER";

public SchedulerDbHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
    String query = "CREATE TABLE " + TABLE_NAME + "(" + TASK_NAME + " TEXT PRIMARY KEY, " +
            TASK_YEAR + " INTEGER, " + TASK_MONTH + " INTEGER, " + TASK_DAY + " INTEGER, " +
            TASK_HOUR + " INTEGER, " + TASK_MINUTE + " INTEGER, " + TASK_DESCRIPTION + " TEXT, " +
            TASK_OWNER + " TEXT" + ")";
    sqLiteDatabase.execSQL(query);
}

@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
    String query = "DROP TABLE IF EXISTS " + TABLE_NAME;
    sqLiteDatabase.execSQL(query);
    onCreate(sqLiteDatabase);
}

public void addTask(Task task) {
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();

    values.put(TASK_NAME, task.getTaskName());
    values.put(TASK_YEAR, task.getYear());
    values.put(TASK_MONTH, task.getMonth());
    values.put(TASK_DAY, task.getDay());
    values.put(TASK_HOUR, task.getHour());
    values.put(TASK_MINUTE, task.getMinute());
    values.put(TASK_DESCRIPTION, task.getDescription());
    values.put(TASK_OWNER, loginID);

    db.insert(TABLE_NAME, null, values);
    db.close();
}

public Task getTask(String taskName){
    SQLiteDatabase db = this.getReadableDatabase();

    Cursor cursor = db.query(TABLE_NAME, new String[]{TASK_NAME, TASK_YEAR, TASK_MONTH, TASK_DAY, TASK_HOUR, TASK_MINUTE, TASK_DESCRIPTION, TASK_OWNER}, TASK_NAME + " =?",
            new String[]{taskName}, null, null, null, null);

    if (cursor != null){
        cursor.moveToFirst();
    }

    Task task = new Task(cursor.getString(0), Integer.parseInt(cursor.getString(1)), Integer.parseInt(cursor.getString(2)),
            Integer.parseInt(cursor.getString(3)), Integer.parseInt(cursor.getString(4)), Integer.parseInt(cursor.getString(5)),
            cursor.getString(6)) ;

    return task;
}

public ArrayList<Task> getAllTask(){
    ArrayList<Task> taskList = new ArrayList<>();

    String selectQuery = "SELECT * FROM " + TABLE_NAME;

    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);

    if (cursor.moveToFirst()) {
        do {
            Task task = new Task();
            task.setTaskName(cursor.getString(0));
            task.setYear(Integer.parseInt(cursor.getString(1)));
            task.setMonth(Integer.parseInt(cursor.getString(2)));
            task.setDay(Integer.parseInt(cursor.getString(3)));
            task.setHour(Integer.parseInt(cursor.getString(4)));
            task.setMinute(Integer.parseInt(cursor.getString(5)));
            task.setDescription(cursor.getString(6));
            taskList.add(task);

        } while (cursor.moveToNext());
    }

    return taskList;
}

public int updateTask(Task task){
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(TASK_NAME, task.getTaskName());
    values.put(TASK_YEAR, task.getYear());
    values.put(TASK_MONTH, task.getMonth());
    values.put(TASK_DAY, task.getDay());
    values.put(TASK_HOUR, task.getHour());
    values.put(TASK_MINUTE, task.getMinute());
    values.put(TASK_DESCRIPTION, task.getDescription());

    return db.update(TABLE_NAME, values, TASK_NAME + "=?", new String[]{task.getTaskName()});
}

public void deleteTask(Task task){
    SQLiteDatabase db = this.getWritableDatabase();
    db.delete(TABLE_NAME, TASK_NAME + "=?", new String[]{task.getTaskName()});
    db.close();
}

public int getTaskCount() {
    String countQuery = "SELECT * FROM " + TABLE_NAME;
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(countQuery, null);
    cursor.close();

    return cursor.getCount();
}

public ArrayList<Task> getAllTaskForUser(){
    ArrayList<Task> taskList = new ArrayList<>();

    String selectQuery = "SELECT * FROM " + TABLE_NAME + " WHERE " + TASK_OWNER + " = " + loginID;

    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);

    if (cursor.moveToFirst()) {
        do {
            Task task = new Task();
            task.setTaskName(cursor.getString(0));
            task.setYear(Integer.parseInt(cursor.getString(1)));
            task.setMonth(Integer.parseInt(cursor.getString(2)));
            task.setDay(Integer.parseInt(cursor.getString(3)));
            task.setHour(Integer.parseInt(cursor.getString(4)));
            task.setMinute(Integer.parseInt(cursor.getString(5)));
            task.setDescription(cursor.getString(6));
            taskList.add(task);
            loginID = cursor.getString(7);

        } while (cursor.moveToNext());
    }

    return taskList;
}

}

这是运行数据库的主片段的代码:

公共类SchedulerFragment扩展了android.support.v4.app.Fragment {

ListView listViewTaskList;
ArrayList<Task> taskList;
SchedulerDbHelper taskDb;
public static String taskPrimary;


public SchedulerFragment() {
    // Required empty public constructor
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment_scheduler, container, false);
}

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    getActivity().setTitle("Scheduler");

    taskDb = new SchedulerDbHelper(getActivity());
    taskList = taskDb.getAllTaskForUser();
    Iterator<Task> i = taskList.iterator();
    String[] taskNameArray = new String[taskList.size()];
    int index = 0;
    FloatingActionButton floatingActionButtonNewTask = getView().findViewById(R.id.floatingActionButtonNewTask);
    listViewTaskList = getView().findViewById(R.id.listViewTaskList);

    while(i.hasNext()){
        Task t = i.next();
        taskNameArray[index] = t.getTaskName();
        index++;
    }

    try {
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, taskNameArray);
        listViewTaskList.setAdapter(adapter);
    } catch (RuntimeException r1) {

    }

    listViewTaskList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            String taskName = adapterView.getItemAtPosition(i).toString();
            taskPrimary = taskName;
            TaskDetailFragment tdf = new TaskDetailFragment();
            FragmentManager manager = getFragmentManager();
            manager.beginTransaction().replace(R.id.frameLayoutContent, tdf, tdf.getTag()).commit();
        }
    });



    floatingActionButtonNewTask.setOnClickListener(new View.OnClickListener() 
{
        @Override
        public void onClick(View view) {
            NewSchedulerFragment nsf = new NewSchedulerFragment();
            FragmentManager manager = getFragmentManager();
            manager.beginTransaction().replace(R.id.frameLayoutContent, nsf, nsf.getTag()).commit();

        }
    });
}
}

这是我得到的例外:

E/AndroidRuntime: FATAL EXCEPTION: main
              Process: com.example.android.eduhub, PID: 6873
              java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.android.eduhub/com.example.android.eduhub.ContentMainActivity}: android.database.sqlite.SQLiteException: no such column: tth980409 (code 1): , while compiling: SELECT * FROM SCHEDULER_TABLE WHERE OWNER = tth980409
                  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
                  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
                  at android.app.ActivityThread.-wrap12(ActivityThread.java)
                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
                  at android.os.Handler.dispatchMessage(Handler.java:102)
                  at android.os.Looper.loop(Looper.java:154)
                  at android.app.ActivityThread.main(ActivityThread.java:6077)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
               Caused by: android.database.sqlite.SQLiteException: no such column: tth980409 (code 1): , while compiling: SELECT * FROM SCHEDULER_TABLE WHERE OWNER = tth980409
                  at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
                  at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
                  at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
                  at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
                  at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
                  at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37)
                  at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
                  at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1318)
                  at android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1257)
                  at com.example.android.eduhub.SchedulerDbHelper.getAllTaskForUser(SchedulerDbHelper.java:143)
                  at com.example.android.eduhub.SchedulerFragment.onViewCreated(SchedulerFragment.java:55)
                  at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1430)
                  at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1740)
                  at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1809)
                  at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:799)
                  at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2580)
                  at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2367)
                  at android.support.v4.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2322)
                  at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2229)
                  at android.support.v4.app.FragmentManagerImpl.dispatchStateChange(FragmentManager.java:3221)
                  at android.support.v4.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManager.java:3171)
                  at android.support.v4.app.FragmentController.dispatchActivityCreated(FragmentController.java:192)
                  at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:560)
                  at android.support.v7.app.AppCompatActivity.onStart(AppCompatActivity.java:177)
                  at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1248)
                  at android.app.Activity.performStart(Activity.java:6679)
                  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2609)
                  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707) 
                  at android.app.ActivityThread.-wrap12(ActivityThread.java) 
                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460) 
                  at android.os.Handler.dispatchMessage(Handler.java:102) 
                  at android.os.Looper.loop(Looper.java:154) 
                  at android.app.ActivityThread.main(ActivityThread.java:6077) 
                  at java.lang.reflect.Method.invoke(Native Method) 
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866) 
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756) 

申请已终止。

1 个答案:

答案 0 :(得分:2)

价值必须在引号中。

将您的查询更新为

String selectQuery = "SELECT * FROM " + TABLE_NAME + " WHERE " + TASK_OWNER + " = " + "\"" + loginID + "\"";