Search code examples
javaandroidsqliteandroid-sqlite

Error no such column in SQLite when updating rows


I'm trying to update data in rows in my DB, but i catch error that there's no such column (no such column 'Moscow' or another)

This is DBHelper code:

public static final String tableName = "currentWeather";

public static final String KEY_ID = "_id";
public static final String cityName = "city";
public static final String cityTemp = "temperature";

And creating DB:

sqLiteDatabase.execSQL("create table " + tableName + "(" + KEY_ID + " 
integer primary key autoincrement,"
    + cityName + " text," + cityTemp + " text, " + " UNIQUE(" + cityName + 
"))");

and error shows when i try to execSQl in response:

sqLiteDatabase.execSQL(
                    "UPDATE " + DBHelper.tableName + " SET " + 
DBHelper.cityTemp + "=" +
                            response.body().getForecastMain().getTemp() + " 
WHERE "
                            + DBHelper.cityName + "=" + cityName);

I expect to update temperature data in rows by cityName


Solution

  • cityName and response.body().getForecastMain().getTemp() are strings and they should be passed surrounded with single quotes to the sql statement:

    sqLiteDatabase.execSQL(
        "UPDATE " + DBHelper.tableName + " SET " +  DBHelper.cityTemp + "='" + response.body().getForecastMain().getTemp() + "'" +
        "WHERE " + DBHelper.cityName + " = '" + cityName + "'"
    );
    

    But the recommended and safe way of doing the update is with the use of ContentValues and ? as placeholders for the parameters:

    ContentValues cv = new ContentValues();
    cv.put(DBHelper.cityTemp, String.valueOf(response.body().getForecastMain().getTemp()));
    int rows = sqLiteDatabase.update(
        DBHelper.tableName, 
        cv,
        DBHelper.cityName + " = ?",
        new String[] {cityName}
    );
    

    You can examine the value of the integer variable rows.
    If it is 1 this means that 1 row was updated (because cityName is unique) so the update was successful.