按顺序查询和在哪里不起作用

时间:2017-03-31 07:22:38

标签: android sqlite

我正在尝试使用以下查询获取visit_no

String strNumber = "SELECT visit_no from tracking order by id DESC limit 1 where c_no = '" + string1 + "' ";
Log.d("strNumber:", strNumber);

每当我在日志中运行以上查询相同查询时,而不是实际visit_no,因为稍后我需要使用相同< / strong> visit_no位于查询下方,请参阅visit_no = strNumber

db.execSQL("update csv set visit_no = strNumber where c_no = '" + string1 + "' ");

所以这是完整的方法,我写了一切

public void checkingRecord(String string1) {

  SQLiteDatabase db = this.getWritableDatabase();

  String strNumber = "SELECT visit_no from tracking order by id DESC limit 1 where c_no = '" + string1 + "' ";
  // db.execSQL(strNumber);

  db.execSQL("update csv set visit_no = strNumber where c_no = '" + string1 + "' ");

  db.close();

}

2 个答案:

答案 0 :(得分:1)

documentation所示,WHERE子句必须在 ORDER BY之前

string1包含引号时,一切都会爆炸。您应该使用参数将字符串插入SQL。

如果您有两个查询,则必须执行第一个查询,读取其结果,然后执行第二个查询。 但是可以使用子查询同时执行everythig:

String sql = "UPDATE csv "+
             "SET visit_no = (SELECT visit_no "+
                             "FROM tracking "+
                             "WHERE c_no = ? "+
                             "ORDER BY id DESC "+
                             "LIMIT 1 "+
                            ") "+
             "WHERE c_no = ?";
db.execSQL(sql, new Object[]{ string1, string1 });

答案 1 :(得分:0)

public int checkingRecord(String string1) {
        int visit_no = 0;
        String selectQuery = "SELECT visit_no from tracking order by id DESC limit 1 where c_no = '" + string1 + "' ";

        SQLiteDatabase db = this.getReadableDatabase();
        Cursor c = db.rawQuery(selectQuery, null);

        if (c != null && c.moveToFirst()) {
            visit_no = c.getInt(c.getColumnIndex(KEY_COMPANY_ID));
            c.close();
        }

        db.close();

        return visit_no;
    }

之后:

public int updateRecord(int visit_no, String string1) {

        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put("visit_no", visit_no);

        // Which row to update, based on the ID
        String whereClause = c_no + " = ? ";
        String[] whereArgs = {String.valueOf(string1)};

        int affectedRows = db.update(
                TABLE_NAME,
                values,
                whereClause,
                whereArgs
        );

        return affectedRows;
    }

在您的活动中:

DatabaseHelper databaseHelper = new DatabaseHelper(YourActivity.this);

int visit_no = databaseHelper.checkingRecord();

int update_row = databaseHelper.updateRecord(visit_no, string1);