Android SQLite Exception: no such column - java

I added a date field to my database, but I got an error which sais "No such column named date".
Can anyone point out where is my mistake?
private static final String UID = "id";
private static final String NAME = "Bmi";
private static final String _STATUS = "status";
private static final String WEIGHT = "weight";
private static final String DATE = "curDate";
db.execSQL("CREATE TABLE " + TABLE_NAME + " ( " + UID + " integer primary key autoincrement," +
"" + NAME + " VARCHAR(50), " +
"" + _STATUS + " VARCHAR(255)," +
"" + WEIGHT + " VARCHAR(255)," +
"" + DATE + "TEXT);");

You're missing a space here
"" + DATE + "TEXT);");
It has to be
"" + DATE + " TEXT);");
Note: uninstall and reinstall your app, to get the database re-created on next launch.

First of all it is a bad habit to use name of SQL inbuilt function as a table name correct your 'DATE' name to something else and there is a typo on the same line of DATE rename table and put the space before text like this.
+ CUR_DATE + " TEXT") (CUR_DATE is suggested name).

Related

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
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.
I think you have changed column name or add new one (city). So you can fix it by two ways
By uninstall the application from phone
Add column name in upgrade method.
Example:
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// If you need to add a column
if (newVersion > oldVersion) {
db.execSQL("ALTER TABLE foo ADD COLUMN new_column INTEGER DEFAULT 0");
}
}
The thing is you need to wrap the values after the = sign in single quotations in the UPDATE statement. As for digits they work in both cases.
For example here is the correct syntax
UPDATE currentWeather
SET temperature = 45
WHERE
city = 'Moscow'
But in your code I'm assuming cityName has the value Moscow without the single quotation marks so the converted SQL code will be like this
UPDATE currentWeather
SET temperature = 45
WHERE
city = Moscow
Now the sql interpreter will think Moscow is some database object or column or something and not a literal value. So you need to surround your values in single quotation marks.
Also consider What the data type of response.body().getForecastMain().getTemp() is.
If it's int you have to parse it or something, as the data type of the related column is Text.

Why is my create table QUERY generating this query automatically only for this table? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
These are my Column Names declared in Java
public static final String TABLE_USER = "user_master";
public static final String ID = "id";
public static final String USER_ID = "user_id";
public static final String USER_FULLNAME = "user_fullname";
public static final String USER_MOBILE = "user_mobile";
public static final String USER_TYPE = "user_type";
public static final String USER_STATUS = "user_status";
This the create table statement generated
String USER_MASTER = "CREATE TABLE user_master ( user_id INTEGER PRIMARY KEY, user_fullname TEXT, user_mobile TEXT, user_type TEXT, user_status TEXT ); ";
String USER_MASTER = " CREATE TABLE " + TABLE_USER + " ( "
+ ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ USER_ID + " INTEGER, "
+ USER_FULLNAME + " TEXT, "
+ USER_MOBILE + " TEXT, "
+ USER_TYPE + " TEXT, "
+ USER_STATUS + " TEXT ) ";
CREATE TABLE user_master(user_id INTEGER PRIMARY KEY, user_fullname TEXT, user_mobile TEXT, user_type TEXT, user_statusTEXT )
Here the "user_statusTEXT" the TEXT word is getting appended automatically.
I just don't know why?
I tried it both ways in SQLiteOpenHelper to create this table, it is still not working
It is hard to debug with the code given. However, the datatype specification of a column is optional in Sqlite CREATE TABLE statement see docs, so you could try removing all the TEXT datatypes and see what happens. So,
String USER_MASTER = " CREATE TABLE " + TABLE_USER + " ( "
+ ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ USER_ID + " INTEGER, "
+ USER_FULLNAME + " , "
+ USER_MOBILE + " , "
+ USER_TYPE + " , "
+ USER_STATUS + " ) ";

Query is not returning any data SQLite

I have database with 4 columns int id | String data | String date | int boot and i have some data in it. I have method getRow(String s) when i call it with string for id or data and change query to that option it works but when i´m trying to get row with equal date it won´t pass cursor.moveToFirst condition.
Here is my code:
String CREATE_TABLE = "CREATE TABLE "
+ TABLE_NAME + "(" + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + COLUMN_DATA
+ " TEXT," + COLUMN_DATE + " TEXT," + COLUMN_BOOT + " Integer" + ")";
public String getRowID(String id){
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery("select * from " + TABLE_NAME + " where " + COLUMN_ID + " = " + id, null);
if (c != null && c.moveToFirst()) {
//loggin succes
return "string";
}else return null;
}
public String getRowDate(String date){
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery("select * from " + TABLE_NAME + " where " + COLUMN_DATE + " = " + date, null);
if (c != null && c.moveToFirst()) {
//loggin succes
return "string";
}else return null;
}
myDb.getRowID("1"); returning something
myDb.getRowDate("02122016"); returning null
I have two rows in my database.
1 | 0.19 | 01122016 | 0
2 | 0.19 | 02122016 | 0
Be wary when comparing integers and strings. You may wonder why SQLite would be comparing integers at all since your arguments are strings, until you consider that your raw query looks like this:
select * from TABLE where DATE = 02122016
That value is interpreted as an integer and converted to text, but it loses the leading zero in the process. You can verify this with a sqlite3 shell:
sqlite> select 02122016;
2122016
sqlite> select '02122016' = 02122016;
0 -- false
sqlite> select cast(02122016 as text);
2122016
The simplest fix is to quote the value using a method from DatabaseUtils:
String escaped = DatabaseUtils.sqlEscapeString(date);
String query = "select * from " + TABLE_NAME + " where " + COLUMN_DATE + " = " + escaped;
A better fix would be to use a placeholder argument instead. Note that Android binds all arguments as strings:
String query = "select * from " + TABLE_NAME + " where " + COLUMN_DATE + " = ?";
db.rawQuery(query, new String[]{date});
However, my advice would be to not use rawQuery() and instead use one of the real query() methods. Here's a good example.
Lastly, perhaps you should consider a different format for storing dates. In practice I usually either store an INTEGER column with a unix timestamp (seconds or milliseconds since epoch), or I use a TEXT column with values in the yyyy-MM-dd format since this is implicitly supported by numerous datetime functions in SQLite.

Android SQLite rawQuery with WHERE clause returns search string as column not found

I have created a table called CHEMISTID:
private static final String CREATE_TABLE_CHEMISTID = "CREATE TABLE "
+ CHEMISTID + "(" + KEY_ID + " INTEGER PRIMARY KEY, " + KEY_CHEMISTID
+ " TEXT" + ")";
My insert function works properly but when I run a search query to find if a chemistId is already present using the following query statement:
String selectQuery = "SELECT * FROM " + CHEMISTID +" WHERE " + KEY_CHEMISTID + " = "+ chemistID + ";";
Cursor c = db.rawQuery(selectQuery,null);
My logcat displays the following error message:
E/AndroidRuntime(1169): FATAL EXCEPTION: main
E/AndroidRuntime(1169): android.database.sqlite.SQLiteException: no such column: Spain (code 1): , while compiling: SELECT * FROM chemistIdTable WHERE chemistId = Spain;
Where Spain is a particular chemistId that I have dynamically created in my program.
How should I fix my selectQuery String so that it searches in the column name KEY_CHEMISTID for a particular String chemistId?
You need to quote your strings such as Spain in SQL so they get taken as string literals and not column name identifiers. You can use single quotes like 'Spain' for that.
However it's much better to use ? parameter placeholders instead and supply the parameter values in the selection args array, like:
... KEY_CHEMISTID + "=?" ...
c = db.rawQuery(selectQuery, new String[] { chemistID });
You missed single quote,So change
String selectQuery = "SELECT * FROM " + CHEMISTID +" WHERE " + KEY_CHEMISTID + " = "+ chemistID + ";";
to
String selectQuery = "SELECT * FROM " + CHEMISTID +" WHERE " + KEY_CHEMISTID + " = '"+ chemistID + "';";
Recommended solution is to use parameterized query as
Cursor c = db.query(CHEMISTID, null, KEY_CHEMISTID + "=?",
new String[] { chemistID },null, null, null, null);

Preview static strings in Android Studio?

I'm having some problems reading what the actual SQL query is behind all this java code. This is just an example, though.
Is there an easy way to get the actual string behind this in Android Studio? It's really just a hard-coded string, after all.
private static final String CREATE_TABLE_ARTICLES = "CREATE TABLE " +
TABLE_ARTICLES + "(" + ARTICLES_KEY_ID + " INTEGER PRIMARY KEY, " +
ARTICLES_KEY_NAME + " TEXT, "+ ARTICLES_KEY_PERCENT_FAT + " INTEGER, " +
ARTICLES_KEY_PRICE + " INTEGER, " +
ARTICLES_KEY_SALES_START + " TEXT, " + ARTICLES_KEY_SALES_STOP + " TEXT, " +
ARTICLES_KEY_VOLUME + " INTEGER, " + ARTICLES_KEY_PRODUCT_GROUP + " TEXT)";
I usually use Log.i or Log.d to print out SQL commands to the console for better readability. If you make the string public (temporarily) you can call it from your main activity.
Log.i("SQLTEST", "create_table command: " + YourClass.CREATE_TABLE_ARTICLES);

Categories

Resources