I want to insert data if that headline doesn't exist yet in the database.
This is the error I'm getting for the written query:
near "with": syntax error (code 1): , while compiling: SELECT * FROM movie WHERE headline=Albert Collen
Code:
public boolean Insert(Item item) {
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
Cursor cursor = sqLiteDatabase.rawQuery("SELECT * FROM " + TABLE + " WHERE headline=" + item.getName() , null);
if (cursor.moveToFirst()) {
} else {
contentValues.put("name", item.getName());
long result = sqLiteDatabase.insert(TABLE, null, contentValues);
if (result == -1) {
return false;
} else {
return true;
}
}
cursor.close();
sqLiteDatabase.close();
return true;
}
You should use query parameters
rawQuery("SELECT * FROM movie WHERE headline = ?", new String[] {"Albert Collen"});
to avoid having to escape quotes and other chars.
First of all, result query is wrong. All the string constants are to be quoted, like this
SELECT * FROM movie WHERE headline='Albert Collen';
So, try to compose query like this, perhaps it will help
Cursor cursor = sqLiteDatabase.rawQuery("SELECT * FROM " + TABLE + " WHERE headline='" + item.getName() + "'" , null);
But concatenating a query is not a good idea because it makes at least SQL-injections possible.
For example, it can cause problems when item.getName() contains following line "'; drop table movies;"
Better option would be using bind query variables. Unfortunately, I'm not familiar with how to use java-android with sqlite, so it is better for you to check how to use such a queries in android
Related
i have a table names "highscore"
In the table there is:
id (int) ,
name (string) ,
win(int) ,
draw(int),
loss(int).
I want to make a query that i can get the specific value win from the row , only the integer.. how can i do that? i want to handle sql injection to.
I have a method that update the win, but i need to get the win, increment the value with 1 and then update. My update method is this and it works:
public void updateWin(String playerName, int win) {
SQLiteDatabase db = this.getReadableDatabase();
ContentValues values = new ContentValues();
values.put(Constants.KEY_WIN, win);
db.update(Constants.TABLE_NAME, values, Constants.KEY_PLAYER_NAME + "= ?", new String[]{playerName});
db.close();
}
Anyone can help me please? thanx
Option 1 - Increment according to arithmetic calculation within SQL
You could base the this on the SQL (assuming the table is mytable001 and the player's name is FRED) :-
UPDATE mytable001 SET win = win +1 WHERE playername = 'FRED';
This would do away with the need to query the playername to get the current number of wins as it directly increments the value.
However, this cannot be done via the convenience update method nor a rawQuery you have utilise execSQL.
So the following could be used :-
public boolean incrementWin(String playerName) {
SQLiteDatabase db = this.getWritableDatabase();
String esc_playername = DatabaseUtils.sqlEscapeString(playerName);
String qrysql = "UPDATE " +
Constants.TABLE_NAME +
" SET " +
Constants.KEY_WIN + " = " +
Constants.KEY_WIN + " + 1" +
" WHERE " +
Constants.KEY_PLAYER_NAME + "=" + esc_playername;
db.execSQL(qrysql);
long changes = DatabaseUtils.longForQuery(db,"SELECT changes()",null);
db.close();
return changes > 0;
}
Note if the update couldn't be/ wasn't performed then it would return false.
The use of sqlEscapeString, will escape the playername and I believe offer some protection against SQL Injection.
Option 2 - Retrieve current value, calculate new, update using new :-
public boolean incWin(String playername) {
SQLiteDatabase db = this.getWritableDatabase();
String whereclause = Constants.KEY_PLAYER_NAME + "=?";
String[] wherargs = new String[]{playername};
int win = -1; // default to not update
Cursor csr = db.query(
Constants.TABLE_NAME,
null,
whereclause,
wherargs,
null,
null,
null
);
if (csr.moveToFirst()) {
win = csr.getInt(csr.getColumnIndex(Constants.KEY_WIN)) + 1;
}
csr.close();
if (win < 1) {
db.close();
return false;
}
ContentValues cv = new ContentValues();
cv.put(Constants.KEY_WIN,win);
if (db.update(Constants.TABLE_NAME,cv,whereclause,wherargs) > 0) {
db.close();
return true;
}
db.close();
return false;
}
Note if the update couldn't be/ wasn't performed then it would return false.
This is my database
public void DBCreate() {
SQLITEDATABASE = getActivity().openOrCreateDatabase("FavoritesDB", Context.MODE_PRIVATE, null);
SQLITEDATABASE.execSQL("CREATE TABLE IF NOT EXISTS favorite(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, word VARCHAR, meaning VARCHAR);");
}
This is how I am creating new rows:
String query = "INSERT INTO favorite (word,meaning) VALUES('"+wordd+"', '"+mean+"');";
Cursor c=SQLITEDATABASE.rawQuery("SELECT * FROM favorite WHERE id=?", null);
if (c.moveToFirst())
{
Toast.makeText(getActivity(),"inserted",Toast.LENGTH_LONG).show();
SQLITEDATABASE.execSQL(query);
}
else
{
Toast.makeText(getActivity(),"exists",Toast.LENGTH_LONG).show();
}
How to check data before inserting value into table?
before inserting perform select query and check the cursor size if it is >0 than record already exist .
I am not sure why are you passing null in your query
Cursor c=SQLITEDATABASE.rawQuery("SELECT * FROM favorite WHERE id=?", null);
instead
Cursor c=SQLITEDATABASE.rawQuery("SELECT * FROM favorite WHERE id=?", new String[]{"your id1"});
or
if you want to select all record then
Cursor c=SQLITEDATABASE.rawQuery("SELECT * FROM favorite");
try this code:
Cursor c = SQLITEDATABASE.rawQuery("SELECT * FROM favorite WHERE id=?", new String[]{"your_id_name"});
Log("Cursor Count : " + c.getCount());
if(c.getCount()>0)
{
Toast.makeText(getActivity(),"exists",Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(getActivity(),"inserted",Toast.LENGTH_LONG).show();
SQLITEDATABASE.execSQL(query);
}
And your select query should look like:
String sql ="SELECT PID FROM "+TableName+" WHERE PID="+pidValue;
Options:
If you do not want to repeat any of the values in a column, set the column setting in the CREATE method to "UNIQUE" or even "PRIMARY KEY" if the content should be the primary key to recognize. Thus you can probably avoid any repetitions without having to check.
Loop through the table:
Cursor c = SQLITEDATABASE.rawQuery("SELECT * FROM favorite", null);
if (c.getCount() > 0) {
String searchString = "some word"; // word you are about to insert
while (c.moveToNext()) {
c.moveToFirst();
int colIndex = c.getColumnIndex("word");
String wordInCurrentRow = c.getString(colIndex);
if (!(wordInCurrentRow.equals(searchString))) {
// insert method
} else {
// do nothing
Log.d("word already existing", "nothing to insert");
}
}
}
I have a SQLite database that I am trying to query in order to find all the items of a specific type. Here is the function that I am calling in order to query my database:
Cursor c = dbi.DBGrabTable("LEGS",ExerciseListActivity.this);
Here is the function definition:
public Cursor DBGrabTable(String type, Context ctx){
String query="SELECT * FROM " + DBContract.DBEntry.TABLE_EXERCISES + " WHERE Type=" + type;
DBContract.DBHelper mDBHelper = new DBContract.DBHelper(ctx);
SQLiteDatabase rdb = mDBHelper.getReadableDatabase();
Cursor c = rdb.rawQuery(query,null);
if (c != null)
return c;
else
return null;
}
The error that I am getting is as follows:
android.database.sqlite.SQLiteException: no such column: LEGS (code 1): , while compiling: SELECT * FROM Exercises WHERE Type=LEGS
Therefore I am thinking it has something to do with the SQL query. I am unsure why it is saying "no such column: LEGS" I am trying to query my database to look in my Table named "Exercises" under the column header "Type" and select all the items that have the word LEGS in that column.
Can anyone see what I am doing wrong? A huge thanks in advance!
1 - Check the table definition whether the column and table name available.
2 - If table and column is available and type is text please change your sql query and try it.
String query="SELECT * FROM " + DBContract.DBEntry.TABLE_EXERCISES + " WHERE Type=" + "'" + type + "'";
Use this query and make sure in maintenace of space and inverted comma. Check your Column name(Type) in TABLE_EXERCISES.
"SELECT * FROM " + DBContract.DBEntry.TABLE_EXERCISES + " WHERE Type = '" + columnValue + "'";
move the cursor till last row of table.
if (cursor != null) {
if (cursor.getCount() > 0) {
cursor.moveToFirst();
do {
} while (cursor.moveToNext());
}
}
How can I detect when an element doesn't exist in my table? I need because I want to update/insert contacts on it. My problem it's that I want to insert a new contact by using ContentObserver but this element is called multiple times and I'm selecting the last element. So when i insert a new contact, I select the last element, I'm trying to identify if exists on the db and insert it.
use a boolean value to check whether the contact exist or not
boolean contact = myDbHelper.checkidExitsorNot(ur table name,row name , value);
public boolean checkidExitsorNot(String tablename, String rowname, String id) {
String queryf = "select * from " + tablename + " where " + rowname + "='" + Integer.valueOf(id) + "'";
Cursor c = myDataBase.rawQuery(queryf, null);
if (c.getCount() == 0) {
c.close();
return true;
}else {
c.close();
return false;
}
}
if the return is true then it does not exist if false it exist
You can check by using count(*) function in database.
Sorry if this seems obvious. I'm trying to write a method to delete a row from a String showId. What would be the best way, and can Cursors only be used for Selects or also for Deletes and Updates?
These are the two methods I'm at so far:
public int deleteShowById1(String showId){
Cursor cursor = db.rawQuery("DELETE FROM tblShows WHERE showId = '" + showId+"'", null);
if (cursor.moveToFirst()) {
return 1;
} else
return -1;
}
public int deleteShowById2(String showId) {
String table_name = "tblShows";
String where = "showId='"+showId+"'";
return db.delete(table_name, where, null);
}
As we know from mysql query, it is same here in android.
String query = "DELETE FROM " +TABLE_NAME+ " WHERE " + COLUM_NAME+ " = " + "'"+VALUE +"'" ;
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL(query);
db.close();
VALUE may or may not have single quotation depending on datatype.
I tend to use the second method (db.delete), as I think using rawQuery is frowned upon.
If you do a select, then loop through the cursor to do updates or deletes, that would make sense, but to pass a cursor to do the delete or update doesn't make sense to me, as the program won't know how to parse the cursor results to get the correct fields.