I know there is probably a simple thing I'm missing, but I've been beating my head against the wall for the past hour or two. I have a database for the Android application I'm currently working on (Android v1.6) and I just want to insert a single record into a database table. My code looks like the following:
//Save information to my table
sql = "INSERT INTO table1 (field1, field2, field3) " +
"VALUES (" + field_one + ", " + field_two + ")";
Log.v("Test Saving", sql);
myDataBase.rawQuery(sql, null);
the myDataBase variable is a SQLiteDatabase object that can select data fine from another table in the schema. The saving appears to work fine (no errors in LogCat) but when I copy the database from the device and open it in sqlite browser the new record isn't there. I also tried manually running the query in sqlite browser and that works fine. The table schema for table1 is _id, field1, field2, field3.
Any help would be greatly appreciated. Thanks!
Your query is invalid because you are providing 2 values for 3 columns. Your raw query should look like:
sql = "INSERT INTO table1 (field1, field2) " +
"VALUES (" + field_one + ", " + field_two + ")";
although your schema contains three fields. By the way, you can see the log to see the actual error reporting from sqlite.
The right answer is given by the CommonsWare in comments. You should be using execSql() instead of rawQuery(). And it works like a charm.
I thought it would be useful for others, not to have to dig through the comments to find the right answer.
Since it is a string values you forgot "'" to add...this query will surely work, i tested
sql = "INSERT INTO table1 (field1, field2) " +
"VALUES ('" + field_one + "', '" + field_two + "')";
I changed my code to use myDataBase.insert() instead of rawQuery() and it's working. I'm not sure why the actual sql query didn't work though, so if anyone can shed some light on that I'd still appreciate it.
Related
I am trying to insert data in database but it is giving me following error.
table places has no column named PLACE_NAME (code 1): , while compiling: INSERT INTO places(PLACE_NAME,IS_SELECTED,placeID,LONGITUDE,LATITUDE) VALUES (?,?,?,?,?)
here is how I am creating my Database Table
// Create a table to hold the places data
final String SQL_CREATE_PLACES_TABLE = "CREATE TABLE IF NOT EXISTS " + PlaceContract.PlaceEntry.TABLE_NAME + " (" +
PlaceContract.PlaceEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + PlaceContract.PlaceEntry.COLUMN_PLACE_NAME + " VARCHAR, " +
PlaceContract.PlaceEntry.COLUMN_PLACE_LATITUDE + " VARCHAR, " + PlaceContract.PlaceEntry.COLUMN_PLACE_LONGITUDE + " VARCHAR, "+
PlaceContract.PlaceEntry.COLUMN_PLACE_IS_SELECTED + " VARCHAR, " +
PlaceContract.PlaceEntry.COLUMN_PLACE_ID + " TEXT NOT NULL, " +
"UNIQUE (" + PlaceContract.PlaceEntry.COLUMN_PLACE_ID + ") ON CONFLICT REPLACE" +
"); ";
please help me what I am doing wrong ....
The most common causes of column not found are typing errors and a misconception in regards to the onCreate method.
The former is unlikely if you are consistently using a single source for the column name e.g. if you use PlaceContract.PlaceEntry.COLUMN_PLACE_NAME to refer to the place_name column.
With the latter, the onCreate method only runs automatically when the database is created, any changes made to the schema, such as adding columns, will not be applied. Thus if you changed the CREATE SQL string to add the PLACE_NAME column that column will not be added.
When developing an App and when the data can be lost then then there are three quick ways to rectify the situation.
Delete the App's data and rerun (the database will be deleted (unless the database is stored outside of the App (not recommended and not the typical scenario))).
Uninstall the App and rerun (also delete's the App's data).
IF the onUpgrade will drop the said table or tables and then recreate the tables (generally by calling the onCreate method) then the database version can be increased (this is the 4th parameter of the super call when constructing the Database Helper class (i.e. the class that extends SQLiteOpenHelper)).
If the data in the database cannot be lost, then the alternative is to use the ALTER to add the column or to create another table, copy the data from the original table and then drop the original table and use ALTER to rename the new table to be the original table.
I'm writing a function for an Android app, that should get the first 8 entries (names of cities) of a database which are matching a string.
This is my query:
Cursor cursor = database.rawQuery(
"SELECT " + CITIES_NAME +
" FROM " + TABLE_CITIES +
" WHERE " + CITIES_NAME +
" LIKE " + String.format("%s%%", nameLetters) +
" LIMIT " + 8
, null);
This is the resulting error:
android.database.sqlite.SQLiteException: near "LIMIT": syntax error (code 1): , while compiling: SELECT city_name FROM CITIES WHERE city_name LIKE berl% LIMIT 8
I have already checked out other questions on the platform, but could not find any solution helping me out. The database is tested and created correctly and also the search entry is in the database.
Could anybody help?
WARNING: You should NOT use string concatenation with the + operator to insert user input in a SQL query.This leaves your app open to a SQL injection attack. I cannot emphasize this enough. Mitigating this common security flaw should be a top priority for all database developers.
Instead, you should use the ? place holder syntax:
String query = "SELECT " + CITIES_NAME +
" FROM " + TABLE_CITIES +
" WHERE " + CITIES_NAME +
" LIKE ?" +
" LIMIT 8";
String[] args = {nameLetters + "%%"};
Cursor cursor = database.rawQuery(query, args);
Even if the database is small and only used for your individual app, it is best to make this syntax a habit. Then when you work on larger, more critical databases, you won't have to worry about this issue as much.
This also has the advantage that it quotes the input for you. You completely avoid the error which you encountered that prompted the original question.
For the sake of completeness I'll turn my comment into an answer, to hopefully help anyone else who may have this issue.
Think you need quotes around the like string eg
SELECT city_name FROM CITIES WHERE city_name LIKE 'berl%' LIMIT 8
Can someone create a greendao (or android sqllite) query to have the same result like the next sql query?
select b.*, a.MAIN_CATEGORY_ID from MAINCATEGORYS_TO_LISTINGS a
join APMAIN_CATEGORY b on b._id=a.MAIN_CATEGORY_ID where listing_id=10120
You could use the queryRaw() method in GreenDao.
If I understand what you are trying to do correctly, e.g.:
session.getMainCategoryDao().queryRaw(
" inner join " + MainCategoryToListingsDao.TABLENAME + " MCL "
+ " on T._id = MCL." + MainCategoryToListingsDao.Properties.MainCategoryId.columnName
+ " where MCL." + MainCategoryToListingsDao.Properties.ListingId.columnName
+ " = ?", listing.getId());
It's a little ugly, but should work. Of course you will have to modify based on how your DAOs are named and possibly how you named your properties. But when GreenDao names your primary table in the query, it is aliased by the T and the primary keys are _id
They rest you can pull by using the DAO's properties.
This will be supported in greenDAO 1.4, which will be released soon. If want you can build greenDAO from the "join" branch for an early version of it: https://github.com/greenrobot/greenDAO/tree/join
Is there a way of closing all cursors that have been used to query a certain database?
I DonĀ“t have the variable names, need a "close.all" sort of code.
Suppose you have some of these cursors, managed by external libraries (Parse Offline DataStore), not by your own code:
Cursor cursorvariablenames = database.rawQuery
("SELECT " + NAME + " FROM " + TABLE_NAME + " WHERE " + DAY_PERIOD[day_counter * 2]
+ " = '" + day + "' AND " + DAY_PERIOD[day_counter * 2 + 1] + " = "
+ Integer.toString(period), null);
I know the name of the sqlite DB = (ParseOfflineStore), and would like to close all cursors that are used by or point toward this DB.
I'll answer my own question to this: There's no solution at sight, no response from Parse team neither.
I am now using SharedPreferences file to handle local data to feed the widget. Any use of Parse Local Datastore will yield into cursor errors over time.
Hope this help someone experiencing the same problem while querying local sqlite databases from homescreen widgets and/or services.
You may try closing your DB withdb.close(); or dbHelper.close();, then all cursors operating on that database should be closed.
I am getting the value from webservice. I am storing in sqlite. While storing in sqlite, I am getting an error. even I replaced single quote with "\'". Which characters are not supported in sqlite?
My error is:
03-26 13:22:22.478: WARN/System.err(311): android.database.sqlite.SQLiteException: near "s": syntax error:
My insert statement is:
myDB.execSQL("INSERT INTO "+TableName
+"("+fieldname+")"
+" VALUES ('"+(homevalue)+"');");
Can anybody tell what to do or give an example?
there is a name which is like "name's" i.e this single quote is problem
Maybe one of your string TableName, fieldname or homevalue contains some quotation. print out the query first and see.
I am just a beginner,
but i think you should write it like this:
"INSERT INTO " + tableName + "(" + feildName + ") VALUES ('" + homeValue + "');"
you put () around the homeValue