public public udpateNoteInfo(String text){
ContentValues val = new ContentValues();
val.put(KEY_CONTENT5, text);
sqLiteDatabase.update(MYDATABASE_TABLE, val,"ORDER_BY("+KEY_ID+") DESC LIMIT 0,1", new String[]{text});
}
I try to update the last row of the KEY_CONTENT5 column in my SQLite, but it's error.
I guess its mistake at "ORDER_BY("+KEY_ID+") DESC LIMIT 0,1" but I don't know how to make it correct. Please tell me if you know that. Thank you.
ERROR:
09-05 11:47:54.769 E/Database( 4386): Error updating note=Test using UPDATE PERSONAL_TABLE SET note=? WHERE _id = (SELECT max(_id) FROM PERSONAL_TABLE)
Activity class:
public void updateNote(String txt) {
mySQLiteAdapter = new PersonalSQLiteAdapter(this);
mySQLiteAdapter.openToWrite();
cursor = mySQLiteAdapter.queueAll();
if (cursor != null) {
mySQLiteAdapter.udpateNoteInfo(txt);
}
mySQLiteAdapter.close();
}
SQLiteAdapter class (not activity):
public void udpateNoteInfo(String text) {
ContentValues val = new ContentValues();
val.put(KEY_CONTENT5, text);
sqLiteDatabase.update(MYDATABASE_TABLE, val, KEY_ID + " = (SELECT max("
+ KEY_ID + ") FROM " + MYDATABASE_TABLE + ")",
new String[] { text });
}
You can't put an order by in an update.
You can try something like this:
WHERE id=(SELECT max(id) FROM TABLE) if you want to update the last id, assuming your sequences aren't modified.
public void udpateNoteInfo(String text) {
ContentValues val = new ContentValues();
val.put(KEY_CONTENT5, text);
sqLiteDatabase.update(MYDATABASE_TABLE, val, KEY_ID+" = (SELECT max("+KEY_ID+") FROM "+MYDATABASE_TABLE+")", null);
}
My final answer.
You can query the ID, and then, update this row... if your key_id values are not unique, you'll need to use your primary key column(s) instead of this one...
Cursor cLast = db.query(MYDATABASE_TABLE, [KEY_ID], null, null, null, "ORDER_BY("+KEY_ID+") DESC", "LIMIT 0,1");
if (cLast.moveToFirst()) {
long lastKey = cLast.getLong(0); // if it's not a long, use the appropriate getter
sqLiteDatabase.update(MYDATABASE_TABLE, val, "WHERE KEY_ID=?", lastKey);
}
UPDATE table set col = 1 WHERE id = (SELECT MAX(id) FROM table)
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.
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);
}
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.
My app has a sqlite table which has the following columns:
CONTACT_ID = "_id",
CONTACT_NAME = "con_name",
CONTACT_USERID = "con_userid",
CONTACT_ACCID = "con_accid".
The content of the column con_accid is of type String. The primary key of the table is id. I want to delete data of particular con_accid. For example, I want to delete item names of all items which have con_accid as "raja". I have tried the following different queries but both are not working:
Cursor cursor = database.query(ContactsDB.TABLE_CONTACTS, allColumns,
ContactsDB.CONTACT_ACCID + "= ' " + comment +"'" , null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Log.i(TAG, "delete");
ContactsInfo _comment = cursorToComment(cursor);
long id = _comment.getId();
database.delete(ContactsDB.TABLE_CONTACTS, ContactsDB.CONTACT_ID + "=" + id , null);
cursor.moveToNext();
}
}
and this:
String query = "SELECT * FROM todo WHERE con_accid='" + comment;
Cursor cursor = database.rawQuery(query,null);
This should delete all rows in your database where con_accid = raja:
database.delete(TABLE_CONTACTS, CONTACT_ACCID + " = ?", new String[] {"raja"});
Check "database" instance is created with .getWritableDatabase(). And your query should work without any issue.
I am trying to get the last inserted rowid from a sqlite database in Android. I have read a lot of posts about it, but can't get one to work.
This is my method:
public Cursor getLastId() {
return mDb.query(DATABASE_TABLE, new String[] {KEY_WID}, KEY_WID + "=" + MAX(_id), null, null, null, null, null);}
I have tried with MAX, but I must be using it wrong. Is there another way?
Well actually the SQLiteDatabase class has its own insert method which returns the id of the newly created row. I think this is the best way to get the new ID.
You can check its documentation here.
I hope this helps.
Use
SELECT last_insert_rowid();
to get the last inserted rowid.
If you are using AUTOINCREMENT keyword then
SELECT * from SQLITE_SEQUENCE;
will tell you the values for every table.
To get the last row from the table..
Cursor cursor = theDatabase.query(DATABASE_TABLE, columns,null, null, null, null, null);
cursor.moveToLast();
Use moveToLast() in Cursor interface.
From android.googlesource.com
/**
* Move the cursor to the last row.
*
* <p>This method will return false if the cursor is empty.
*
* #return whether the move succeeded.
*/
boolean moveToLast();
Simple example:
final static String TABLE_NAME = "table_name";
String name;
int id;
//....
Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_NAME, null);
if(cursor.moveToLast()){
//name = cursor.getString(column_index);//to get other values
id = cursor.getInt(0);//to get id, 0 is the column index
}
Or you can get the last row when insertion(Which is #GorgiRankovski have mentioned):
long row = 0;//to get last row
//.....
SQLiteDatabase db= this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COLUMN_NAME, name);
row = db.insert(TABLE_NAME, null, contentValues);
//insert() returns the row ID of the newly inserted row, or -1 if an error occurred
Also their is a multiple ways you can do this using query:
One is expressed by #DiegoTorresMilano
SELECT MAX(id) FROM table_name. or to get all columns values SELECT * FROM table_name WHERE id = (SELECT MAX(id) FROM table_name).
If your PRiMARY KEY have sat to AUTOINCREMENT, you can SELECT vaules occording to max to min and limit the rows to 1 using SELECT id FROM table ORDER BY column DESC LIMIT 1
(If you want each and every value, use * instead of id)
If you want the last_insert_id just afert a insert you can use that :
public long insert(String table, String[] fields, String[] vals )
{
String nullColumnHack = null;
ContentValues values = new ContentValues();
for (int i = 0; i < fields.length; i++)
{
values.put(fields[i], vals[i]);
}
return myDataBase.insert(table, nullColumnHack, values);
}
The insert method returns the id of row just inserted or -1 if there was an error during insertion.
long id = db.insert("your insertion statement");
db is an instance of your SQLiteDatabase.
Try this:
public Cursor getLastId() {
return mDb.query(DATABASE_TABLE, new String[] { **MAX(id)** }, null, null, null, null, null, null);}
/**
* #return
*/
public long getLastInsertId() {
long index = 0;
SQLiteDatabase sdb = getReadableDatabase();
Cursor cursor = sdb.query(
"sqlite_sequence",
new String[]{"seq"},
"name = ?",
new String[]{TABLENAME},
null,
null,
null,
null
);
if (cursor.moveToFirst()) {
index = cursor.getLong(cursor.getColumnIndex("seq"));
}
cursor.close();
return index;
}
I use this
public int lastId(){
SQLiteDatabase db =
this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from resep", null );
res.moveToLast();
return res.getInt(0);
}
In your DbHelper class,
public long getLastIdFromMyTable()
{
SQLiteDatabase db = this.getReadableDatabase();
SQLiteStatement st = db.compileStatement("SELECT last_insert_rowid() from " + MY_TABLE);
return st.simpleQueryForLong();
}