android.database.sqlite.SQLiteException: no such column: personal (code 1): - android

I have a table created by this sql command ->
CREATE TABLE messages( id integer primary key autoincrement, senderNum String, messagebody String, label String );
In this Table I have a row having senderNum equal to 123.In order to apply label to it i call method which looks like this ->
public void ApplyLabel(String senderNum){
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("update messages set label=personal where senderNum=" + senderNum,null);
}
where the variable senderNum have value 123.Now when this method is called it throws error like this ->
android.database.sqlite.SQLiteException: no such column: personal (code 1): , while compiling: update messages set label=personal where senderNum=123
I don't know why it gives this error ??

You are missing the string delimiters (') surrounding your string value.
As it's now, you are comparing a column named label to another column named personal, which doesn't exist.
Try:
Cursor res = db.rawQuery("update messages set label='personal' where senderNum=" + senderNum,null);
If you want to use a variable, you can concatenate the string like so:
Cursor res = db.rawQuery("update messages set label='" + strPersonal + "' where senderNum=" + senderNum,null);

Related

How to use _COUNT in BaseColumns

I've been reading up on BaseColumns](https://developer.android.com/reference/android/provider/BaseColumns.html) in Android to help structure my database schema.
I know that _ID is a unique identifier for the row that you have to create yourself:
protected static final String SQL_CREATE = "CREATE TABLE " + TABLE_NAME + "( " +
_ID + " INTEGER PRIMARY KEY AUTOINCREMENT" + ...;
I also read that _COUNT is used to refer to the number of rows in a table.
However, when I tried using _COUNT, I got an error. Here is what I tried:
SQLiteDatabase db = TimetableDbHelper.getInstance(context).getReadableDatabase();
Cursor cursor = db.query(
SubjectsSchema.TABLE_NAME,
new String[] {SubjectsSchema._COUNT},
null, null, null, null, null);
cursor.moveToFirst();
int count = cursor.getInt(cursor.getColumnIndex(SubjectsSchema._COUNT));
cursor.close();
return count;
I'm not sure whether or not this is the correct way to use it, but I got this error:
android.database.sqlite.SQLiteException: no such column: _count (code 1): , while compiling: SELECT _count FROM subjects
How should I be using _COUNT?
In the database, there is nothing special about either _id or _count.
Your queries return an _id or _count column when the table is defined to have such a column, or when the query explicitly computes it.
Many objects of the Android framework expect a cursor to have a unique _id column, so many tables define it.
In most places, the _count is not expected to be present, so it is usually not implemented. And if it is actually needed, it can simply be computed with a subquery, like this:
SELECT _id,
[other fields],
(SELECT COUNT(*) FROM MyTable) AS _count
FROM MyTable
WHERE ...
If you want to find out the size of your own table, you are not required to use the _count name; you can execute a query like SELECT COUNT(*) FROM subjects, or, even simpler, use a helper function that does this for you.

rawQuery() in Android SQLite not compiling parameters

While trying to implement SQLite storage ran into strange behavior.
The "?"-symbols are not substituted.
My code:
public class DBHandler extends SQLiteOpenHelper {
public void writeTask(JSONObject object) throws JSONException {
SQLiteDatabase db = this.getWritableDatabase();
String id = object.get(OBJECT_ID).toString();
String content = object.toString();
String md5 = "md5"; //testing
Cursor c = db.rawQuery("INSERT OR REPLACE INTO ? ( ? , ? , ? ) VALUES ( ? , ? , ?);", new String[] {TABLE_OBJECTS, OBJECT_ID, OBJECT_CONTENT, OBJECT_MD5, id, content, md5 });
}
}
Then it throws a strange error:
android.database.sqlite.SQLiteException: near "?": syntax error (code 1): , while compiling: INSERT OR REPLACE INTO ? ( ? , ? , ? ) VALUES ( ? , ? , ?);
First mistake corrected, but still not working:
String selectQuery = "INSERT OR REPLACE INTO " + TABLE_OBJECTS + " ("
+ OBJECT_ID + "," + OBJECT_CONTENT + "," + OBJECT_MD5 + ") "
+ "VALUES ( ? , ? , ?);";
String[] args = { id, content, md5 };
Log.d("FP", selectQuery);
Cursor c = db.rawQuery(selectQuery,args);
Now database is untouched after this query. Logs show my query:
INSERT OR REPLACE INTO objects (id,content,md5) VALUES (?,?,?);
Any suggestions?
so, rawQuery() is just for SELECT.
But i still need to do escaping special characters, because content-variable is a stringified JSON and execSQL does not allow this.
You can use ? only for binding literals such as those in your VALUES(), not for identifiers such as table or column names earlier in your SQL.
If you need to use variables for identifiers, use regular string concatenation in Java.
Also note that rawQuery() alone won't execute your SQL. Consider using execSQL() instead.

error occurs when updating a table in sqlite

String updateQuery = "UPDATE Bookdetails SET lastchapter = " + test + " WHERE bookpath=" +sentFilename;
db.execSQL(updateQuery);
Error:
03-04 13:36:23.997: I/System.out(9722): android.database.sqlite.SQLiteException:
near "/": syntax error: , while compiling: UPDATE Bookdetails SET lastchapter =
mukund WHERE bookpath=/mnt/sdcard/Download/What's so great about the doctrine of
grace.epub errors happens
the error is posted above
My table contains the field id, bookpath and lastchapter, book path contains the values
/mnt/sdcard/Download/What's so great about the doctrine of grace.epub
/mnt/sdcard/Download/1b4fdaac-f31d-41e8-9d15-26c9078d891f.epub
/mnt/sdcard/Download/Commentary on Romans.epub
and lastchapter contains the values nothing nothing nothing
id contains 1 2 3
why is the error occurring at "/" there is no hash in my update query it is only there at string which stores bookpath? Is this an error?
String literals in SQL need to be in '' quotes.
However, it's better to use ? placeholders for literals like this:
String updateQuery = "UPDATE Bookdetails SET lastchapter=? WHERE bookpath=?";
db.execSQL(updateQuery, new String[] { test, sentFilename });
I believe your lastchapter & bookpath is of type String (TEXT). Hence when you are adding or updating it's value you should always use ' ( Single cot ) around it. Change your query to this,
String updateQuery = "UPDATE Bookdetails SET lastchapter ='" + test + "' WHERE bookpath='" +sentFilename + "'";
db.execSQL(updateQuery);
However, Direct Execution of SQL query is not advisable at developer.android.com hence you can use alternative way like below code,
String updateQuery = "UPDATE Bookdetails SET lastchapter=? WHERE bookpath=?";
db.execSQL(updateQuery, new String[] { test, sentFilename });

syntax error while compiling sqlite

I'm trying to make a new table for my database with sqlite:
String CREATE_ARCHIVE_TABLE =
"CREATE TABLE {0} ({1} INTEGER PRIMARY KEY AUTOINCREMENT," +
" {2} TEXT NOT NULL, {3} TEXT NOT NULL, {4} TEXT NOT NULL, {5} INTEGER);";
db.execSQL(MessageFormat.format(CREATE_ARCHIVE_TABLE,AItext.TABLE_NAME,AItext._ID,
AItext.TITLE,AItext.MESSAGE,AItext.DATE,AItext.TYPE));
with the interface:
public interface AItext extends BaseColumns {
String TABLE_NAME = "table_name";
String TITLE = "title";
String MESSAGE = "message";
String DATE = "date";
String TYPE = "type";
String[] COLUMNS = new String[]
{ _ID, TITLE, MESSAGE, DATE, TYPE };
}
but I have the following exception and I can't see the error
android.database.sqlite.SQLiteException: near "INTEGER": syntax error: ,
while compiling: CREATE TABLE archive_contacts_name (_id INTEGER PRIMARY KEY
AUTOINCREMENT, message INTEGER, name TEXT NOT NULL, phone TEXT NOT NULL,
check INTEGER, note TEXT NOT NULL);
As #aim has said, CHECK is in fact a SQLite Keyword that cannot be used as a column name.
A CHECK constraint may be attached to a column definition or specified as a table constraint. In practice it makes no difference. Each time a new row is inserted into the table or an existing row is updated, the expression associated with each CHECK constraint is evaluated and cast to a NUMERIC value in the same way as a CAST expression. If the result is zero (integer value 0 or real value 0.0), then a constraint violation has occurred. If the CHECK expression evaluates to NULL, or any other non-zero value, it is not a constraint violation. The expression of a CHECK constraint may not contain a subquery.
CHECK constraints have been supported since version 3.3.0. Prior to version 3.3.0, CHECK constraints were parsed but not enforced.

SQLite rawquery

I am getting an error with a rawquery on Eclipse on a DB in the assets directory. The DB is 'pre-loaded' with tables and data and the SQL string, first comment line, works in SQLite DB browser. When I copy the SQL string to code and modify to remove quotes it errors. The code below is from the 'standard' public class DataBaseHelper extends SQLiteOpenHelper{ .I am new to android/java and would appreciate any assistance or suggestions.
public Cursor getAllSectionDescriptions( String DBtable, String source){
//Works in DB: SELECT "Description" FROM "SectionProps" WHERE Source = "UK"
//String q = "SELECT Description FROM SectionProps WHERE Source = UK " ; <= errors in code
String q = "SELECT Description FROM " + DBtable + " WHERE Source = " + source + " "; //<== errors in code
//06-24 16:53:03.373: ERROR/AndroidRuntime(1000): Caused by: android.database.sqlite.SQLiteException: no such table: SectionProps: , while compiling: SELECT Description FROM SectionProps WHERE Source = UK
Cursor mCursor = myDataBase.rawQuery(q, null);
mCursor.moveToFirst();
return mCursor;
}//end cursor
Looks like you have to put double quotes around your object names. So you'll want to do this:
String q = "SELECT \"Description\" FROM \"" + DBtable + "\" WHERE Source = \"" + source + "\" ";
Note the double quotes preceded by the escape character '\'
To execute queries, there are two methods: Execute db.rawQuery method Execute db.query method To execute a raw query to retrieve all departments:
Cursor getAllDepts()
{
SQLiteDatabase db=this.getReadableDatabase();
Cursor cur=db.rawQuery("SELECT "+colDeptID+" as _id,
"+colDeptName+" from "+deptTable,new String [] {});
return cur;
}
The rawQuery method has two parameters: String query: The select statement String[] selection args: The arguments if a WHERE clause is included in the select statement Notes The result of a query is returned in Cursor object. In a select statement if the primary key column (the id column) of the table has a name other than _id, then you have to use an alias in the form SELECT [Column Name] as _id cause the Cursor object always expects that the primary key column has the name _id or it will throw an exception .

Categories

Resources