Get a specific value from a specific column from specific row? - android

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.

Related

Insert if not exists: SQLite

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

Update values of a specific column of a specific row. Android SQLite

I have a recyclerview cardholder that inflates using the values of 'NAME' from the table 'ORDERTABLE'. The cardholder also have an EditText which displays the values of column 'QUANTITY' in my SQLite database.
I also have a button to update the database for every changes in EditText.
I have this table ORDERTABLE
id NAME QUANTITY
1 Order1 1
2 Order2 1
3 Order3 1
4 Order4 1
Being more specific, how can i update the QUANTITY of Order2 on onButtonPressed with the new values of my EditText.
EDIT...
I have tried this code but nothing happened
Button to update values
public void addButtonClick(TextView tv_cardrowName_atc, TextView tv_currentPrice_atc, EditText et_quantity_atc, int position) {
int thisQuantity = Integer.parseInt(et_quantity_atc.getText().toString());
thisQuantity++;
String orderName = tv_cardrowName_atc.getText().toString();
String oldQuantity = et_quantity_atc.getText().toString();
String newQuantity = String.valueOf(thisQuantity);
sqliteCBLCAdapter.selectUpdateItem(orderName, oldQuantity, newQuantity);
et_quantity_atc.setText(String.valueOf(thisQuantity));
}
Update Method
public String selectUpdateItem(String orderName, String oldQuantity, String newQuantity) {
SQLiteDatabase sqLiteDatabase = sqLiteCBLC.getWritableDatabase();
String[] columns = {SQLiteCBLC.COL_ORDNAME, SQLiteCBLC.COL_QUANTITY};
Cursor cursor = sqLiteDatabase.query(SQLiteCBLC.TABLE_NAME, columns, SQLiteCBLC.COL_ORDNAME + " = '" + orderName + "'", null, null, null, null);
StringBuffer stringBuffer = new StringBuffer();
while (cursor.moveToNext()) {
int index1 = cursor.getColumnIndex(SQLiteCBLC.COL_ORDNAME);
int index2 = cursor.getColumnIndex(SQLiteCBLC.COL_QUANTITY);
String order = cursor.getString(index1);
String quantity = cursor.getString(index2);
ContentValues contentValues = new ContentValues();
contentValues.put(SQLiteCBLC.COL_QUANTITY, newQuantity);
String[] whereArgs = {quantity};
sqLiteDatabase.update(SQLiteCBLC.TABLE_NAME, contentValues, SQLiteCBLC.COL_QUANTITY + " =? ", whereArgs);
stringBuffer.append(order);
}
return stringBuffer.toString();
}
The easiest way for you to achieve this would be to use a SQL update query as follows:
From the SQLite Web Site:
The SQLite UPDATE Query is used to modify the existing records in a table. You can use a WHERE clause with UPDATE query to update selected rows, otherwise all the rows would be updated.
The syntax for the update query is as follows:
UPDATE table_name
SET column1 = value1, column2 = value2...., columnN = valueN
WHERE [condition];
So in your case your sql update query would look some thing like this:
UPDATE ORDERTABLE SET QUANTITY = (INSERT VALUE OF YOUR EDIT TEXT) WHERE NAME = 'Order2'
You can then execute your query by using the execSQL() method of your SQLiteDatabase object that you have and passing in the sql query above as the string parameter.
You can try like this below code, In your case you while updating you are updating based on quantity, multiple order will have the same quantity. just check the order name and update it.
public void selectUpdateItem(String orderName, String oldQuantity, String newQuantity) {
if (TextUtils.isEmpty(order)) {
return;
}
ContentValues contentValues = new ContentValues();
final String whereClause = SQLiteCBLC.COL_ORDNAME + " =?";
final String[] whereArgs = {
orderName
};
// if you want to update with respect of quantity too. try this where and whereArgs below
//final String whereClause = SQLiteCBLC.COL_ORDNAME + " =? AND " + SQLiteCBLC.COL_QUANTITY + " =?";
//final String[] whereArgs = {
//orderName, String.valueOf(oldQuantity)
//};
contentValues.put(SQLiteCBLC.COL_QUANTITY, newQuantity);
SQLiteDatabase sqLiteDatabase = sqLiteCBLC.getWritableDatabase();
sqLiteDatabase.update(SQLiteCBLC.TABLE_NAME, contentValues,
whereClause, whereArgs);
}

Can not Update Sqlite Database with Cursor and Calling onClickListener

This is Method Cursor on DatabaseHelper;
public Cursor updateNewQuiz(int n, String s) {
return getWritableDatabase().rawQuery("UPDATE tb_characters SET LOCKED = '" + s + "' WHERE ID = '" + n + "'", null);
}
public Cursor updateThisQuiz(int n) {
return getWritableDatabase().rawQuery("UPDATE tb_characters SET ANSWERED = '1' WHERE ID = '" + n + "'", null);
}
And, I was Calling OnClickLIstener in Acticity like this
int nn = Integer.parseInt(resultes0);
int s = Integer.parseInt(resultes0);
Cursor cursor = myDb.updateNewQuiz(nn+1,"1");
Cursor cursor1 = myDb.updateThisQuiz(s);
But, my database it still Does not UPDATE...
Please Help Me ....
The documentation says:
A string constant is formed by enclosing the string in single quotes (').
So ... WHERE ID = '" + n + "' ... searches for a row that has a string as the ID. There is no such row, so nothing gets updated.
In SQL, you must write numbers without quotes:
... WHERE ID = " + n + " ...
Furthermore, you must use execSQL() to execute statements that are not SELECT queries.
It might be a better idea to use update() instead:
ContentValues cv = new ContentValues();
cv.put("LOCKED", 1);
db.update("tb_characters", cv, "ID = " + n, null);

Looking for record in Android SQlite Database by String

public boolean findContact(String phoneNumber) {
boolean exists = false;
Cursor mCursor = mDb.rawQuery("SELECT * FROM " + SQLITE_TABLE + " WHERE " + KEY_PHONENUMBER + " = " + phoneNumber, null);
if (mCursor.moveToFirst()) {
exists = true;
} else exists = false;
return exists;
}
It is supose to return true when a row with telephone number exists (format is +441212312312 - String ). The problem is that it always return false, even if such a row exists. I think that a problem is with WHERE clause, but LIKE don't work either. How can I do this ?
thanks for your response
i suggest you that use query, insert, update or delete clauses directly from SQLiteDatabase object instance ;)
And see link below to know which values you will have returned
SQLiteDatabase Object
And i suggest too that if you just want if it exists don't ask about * ... ask about _id because it's primary key it has a index ;)) <-- it means faster
Here i seek a specific row:
public Cursor getEnvio(final String empresa_p, final String albaran_p) {
return db.query(Envio.KEY_ENVIO, new String[] { Envio.KEY_ID,
Envio.KEY_ALBARAN, Envio.KEY_LINEA, Envio.KEY_TIPO,
Envio.KEY_DESTINATARIO, Envio.KEY_DIR, Envio.KEY_POBLACION,
Envio.KEY_POBLACION, Envio.KEY_PRIORIDAD, Envio.KEY_INCIDENCIA,
Envio.KEY_EMP, Envio.KEY_CPOSTAL }, Envio.KEY_EMP + " = ? AND "
+ Envio.KEY_ALBARAN + " = ? ", new String[] { empresa_p,
albaran_p }, null, null, Envio.KEY_LINEA);
}

Insert or update in SQlite and Android using the database.query();

is there a way to change my function:
public categorie createCategoria(String categoria) {
ContentValues values = new ContentValues();
values.put(MySQLiteHelper.COLUMN_NOME, categoria);
values.put(MySQLiteHelper.COLUMN_PREF, 0);
long insertId = database.insert(MySQLiteHelper.TABLE_CATEGORIE, null,
values);
Cursor cursor = database.query(MySQLiteHelper.TABLE_CATEGORIE,
allCategorieColumns, MySQLiteHelper.COLUMN_ID + " = " + insertId, null,
null, null, null);
cursor.moveToFirst();
categorie newCategoria = cursorToCategorie(cursor);
cursor.close();
return newCategoria;
}
this is a raw insert, i would like to change this function to make it update or insert accordingly. i would like to change this becouse i'm already using this function in some places, but now i need to choose if insert a row or update (or ignoring the insert) a row with the same COLUMN_NOME. can someone help me doing this?
i mean i would like to insert a new row ONLY if there isn't another with the same name (as usual you know).
You can use insertWithOnConflict() if you want to insert or update, depending in whether the record exists or not:
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COLUMN_ID, id);
contentValues.put(COLUMN_VALUE, value);
// this will insert if record is new, update otherwise
db.insertWithOnConflict(TABLE, null, contentValues, SQLiteDatabase.CONFLICT_REPLACE);
you could call int nRowsEffected = database.update(...); if there are no rows effected by the update either the row doesn't exist (or you hosed your update()!) therefore you need to call database.insert(...). of course if nRowsEffected > 0 then you are done.
You can use execSQL and use INSERT OR REPLACE
String[] args = {"1", "newOrOldCategory"}; // where 1 is the category id
getWritableDatabase().execSQL("INSERT OR REPLACE INTO table_name (idColoumn, categoryColumn) VALUES (?, ?)", args);
First of all you have write function which is check whether id is exists in particular Table like:
/**
* #param table_name
* #param server_id
* #return
*/
public boolean isServerIdExist(String table_name, int server_id) {
long line = DatabaseUtils.longForQuery(mDB, "SELECT COUNT(*) FROM " + table_name + " WHERE id=?",
new String[]{Integer.toString(server_id)});
return line > 0;
}
You have to pass table_name and id in that like
/**
* INSERT in TABLE_ACCOUNT_DEVICE
**/
public long insertOrUpdateAccountDevice(int server_id, int account_id,
String device_name, String device_id,
String last_active, String itp,
String utp, int status) {
ContentValues values = new ContentValues();
values.put(ACCOUNT_DEVICE_ACCOUNT_ID, account_id);
values.put(ACCOUNT_DEVICE_DEVICE_NAME, device_name);
values.put(ACCOUNT_DEVICE_DEVICE_ID, device_id);
values.put(ACCOUNT_DEVICE_LAST_ACTIVE, last_active);
values.put(ACCOUNT_DEVICE_ITP, itp);
values.put(ACCOUNT_DEVICE_UTP, utp);
values.put(ACCOUNT_DEVICE_STATUS, status); // 0=pending, 1=active, 2=Inactive, -1=not_found
/**
* isServerIdExists
*/
if (isServerIdExists(TABLE_ACCOUNT_DEVICE, server_id)) {
values.put(ACCOUNT_DEVICE_SERVER_ID, server_id);
return mDB.insert(TABLE_ACCOUNT_DEVICE, null, values);
} else {
return mDB.update(TABLE_ACCOUNT_DEVICE, values, ACCOUNT_DEVICE_SERVER_ID + " =? ",
new String[]{Integer.toString(server_id)});
}
}
Hope it will helps you.

Categories

Resources