I want to write a Query to delete a row from the table. I am confused of writing the statement. I need some help in writing this. I am providing my requirement here with plain sql statement.
(Pseudo code)
delete from tablename where value =="string1" && value2 == "string2" && value3 == "string3";
I want to write this in the Sqlite syntax for android db.delete(tablename, whereclause, whereargs);.
I would be thankful for your help.
a better way would be to use
String where = "value1 = ?"
+ " AND value2 = ?"
+ " AND value3 = ?";
String[] whereArgs = {string1,string2,string3};
String table_name = "myTable";
String where = "value1 = 'string1'"
+ " AND value2 = 'string2'"
+ " AND value3 = 'string3'";
String whereArgs = null;
mDb.delete(table_name, where, whereArgs);
mdb.delete("tablename",new String("value1=? and Value2=? and value3=?"),new String[]{value1,value2,value3});
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("DELETE FROM tablename WHERE value1='"+string1+"' AND value2='"+string2+"' AND value3='"+string3+"' "); //delete row in a table with the condition
db.close();
Related
I have a table and I want to update the existing values when the count is greater is 1.
Here is my code :
public int getCount(String clues) {
Cursor c = null;
try {
db = this.getReadableDatabase();
String query = "select count(*) from " + TABLE_NAME + "where CLUES_VALUES = ?";
c = db.rawQuery(query, new String[] {clues});
if (c.moveToFirst()) {
return c.getInt(0);
}
return 0;
}
finally {
if (c != null) {
c.close();
}
if (db != null) {
db.close();
}
}
}
I am checking based on the column "CLUES_VALUES" . I am getting the values from database and checking if it contains more than one similar value in the column of "CLUES_VALUES" . If it contains then it will update the entire row else it won't.
when I am executing the code, I am getting below error
android.database.sqlite.SQLiteException: near "=": syntax error (code 1): , while compiling: select count(*) from puzzl_tablewhere CLUES_VALUES = ?
Clues_values column contains "String values"
I don't know where I am missing. Please help .
You're missing a space in front of "where".
String query = "select count(*) from " + TABLE_NAME + " where CLUES_VALUES = ?";
I think what you are missing is simply a space after table name and before where.
String query = "select count(*) from " + TABLE_NAME + " where CLUES_VALUES = ?";
SQLite delete query isn't working. Can anyone tell me how to use db.delete(table, whereClause, whereArgs) method in limit query?!
String query = "DELETE From gpsinfo LIMIT 100 ";
Cursor cursor = db.rawQuery(query, null);
Try this...
Delete from table_name where ID IN (Select ID from table_name limit 100 );
Use execSQL() for SQL like this.
rawQuery() doesn't run the SQL until you move the returned cursor.
Also, you cannot use LIMIT like this.
String query = "DELETE FROM " +TABLE_NAME+ " WHERE " + COLUMN_NAME+ " = " + "'"+text+"'" ;
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL(query);
db.close();
In my application, store the amount details of company in my sq lite DB.For example om my first position of DB in name column-company 1,total column - 400,second position of DB in name column-company 2,total column - 800,third position of DB in name column-company 1,total column - 500.how Sum the company 1 details only to return the total amount.
My main coding is,
String str = db.company_amount("Company 1");
Log.v("Total", ""+str);
My DB coding is,
String company_amount(String name){
SQLiteDatabase db = this.getReadableDatabase();
String s = "";
Cursor cursor = db.rawQuery("SELECT SUM(KEY_AMOUNT) FROM TABLE_BILL_DETAILS WHERE = ?", new String[] {String.valueOf(name)});
if (cursor != null) {
if (cursor.moveToNext()) {
s = cursor.getString(1);
return cursor.getString(1);
}
cursor.close();
}
return s;
}
It shows some error,I don't know how to return the values.Can any one know please help me to solve this problem.
My Logcat Error
04-25 14:54:06.701: E/AndroidRuntime(2776): FATAL EXCEPTION: main
04-25 14:54:06.701: E/AndroidRuntime(2776): java.lang.RuntimeException: Unable to start activity
ComponentInfo{invoicebill.details/invoicebill.details.Total_company_details}: android.database.sqlite.SQLiteException: near "=": syntax error: , while compiling: SELECT SUM(KEY_AMOUNT) FROM TABLE_BILL_DETAILS WHERE = ?
SQLiteDatabase db = getReadableDatabase();
String sql = "SELECT SUM(KEY_AMOUNT) FROM TABLE_BILL_DETAILS WHERE name = ?";
long sum = android.database.DatabaseUtils.longForQuery(db, sql, new String[]{name});
WHERE = ?
This is incorrect SQL syntax. You forgot to specify which field you're comparing with the argument. I guess it's name or something similar, so correct syntax would be something like:
WHERE name = ?
you can use to get details using id like this.
public int getTotalOfAmount(int id) {
odb = dbh.getReadableDatabase();
Cursor c = odb.rawQuery("SELECT SUM(" + KEY_AMOUNT + ") FROM " + DATABASE_TABLE + " WHERE " + KEY_ID + " = " + id, null);
c.moveToFirst();
int i = c.getInt(0);
c.close();
return i;
}
.
I'm trying to create a simple Login form, where I compare the login id and password entered at the login screen with that stored in the database.
I'm using the following query:
final String DATABASE_COMPARE =
"select count(*) from users where uname=" + loginname + "and pwd=" + loginpass + ");" ;
The issue is, I don't know, how can I execute the above query and store the count returned.
Here's how the database table looks like ( I've manged to create the database successfully using the execSQl method)
private static final String
DATABASE_CREATE =
"create table users (_id integer autoincrement, "
+ "name text not null, uname primary key text not null, "
+ "pwd text not null);";//+"phoneno text not null);";
Can someone kindly guide me as to how I can achieve this? If possible please provide a sample snippet to do the above task.
DatabaseUtils.queryNumEntries (since api:11) is useful alternative that negates the need for raw SQL(yay!).
SQLiteDatabase db = getReadableDatabase();
DatabaseUtils.queryNumEntries(db, "users",
"uname=? AND pwd=?", new String[] {loginname,loginpass});
#scottyab the parametrized DatabaseUtils.queryNumEntries(db, table, whereparams) exists at API 11 +, the one without the whereparams exists since API 1. The answer would have to be creating a Cursor with a db.rawQuery:
Cursor mCount= db.rawQuery("select count(*) from users where uname='" + loginname + "' and pwd='" + loginpass +"'", null);
mCount.moveToFirst();
int count= mCount.getInt(0);
mCount.close();
I also like #Dre's answer, with the parameterized query.
Use an SQLiteStatement.
e.g.
SQLiteStatement s = mDb.compileStatement( "select count(*) from users where uname='" + loginname + "' and pwd='" + loginpass + "'; " );
long count = s.simpleQueryForLong();
See rawQuery(String, String[]) and the documentation for Cursor
Your DADABASE_COMPARE SQL statement is currently invalid, loginname and loginpass won't be escaped, there is no space between loginname and the and, and you end the statement with ); instead of ; -- If you were logging in as bob with the password of password, that statement would end up as
select count(*) from users where uname=boband pwd=password);
Also, you should probably use the selectionArgs feature, instead of concatenating loginname and loginpass.
To use selectionArgs you would do something like
final String SQL_STATEMENT = "SELECT COUNT(*) FROM users WHERE uname=? AND pwd=?";
private void someMethod() {
Cursor c = db.rawQuery(SQL_STATEMENT, new String[] { loginname, loginpass });
...
}
Assuming you already have a Database (db) connection established, I think the most elegant way is to stick to the Cursor class, and do something like:
String selection = "uname = ? AND pwd = ?";
String[] selectionArgs = {loginname, loginpass};
String tableName = "YourTable";
Cursor c = db.query(tableName, null, selection, selectionArgs, null, null, null);
int result = c.getCount();
c.close();
return result;
how to get count column
final String DATABASE_COMPARE = "select count(*) from users where uname="+loginname+ "and pwd="+loginpass;
int sometotal = (int) DatabaseUtils.longForQuery(db, DATABASE_COMPARE, null);
This is the most concise and precise alternative. No need to handle cursors and their closing.
If you are using ContentProvider then you can use:
Cursor cursor = getContentResolver().query(CONTENT_URI, new String[] {"count(*)"},
uname=" + loginname + " and pwd=" + loginpass, null, null);
cursor.moveToFirst();
int count = cursor.getInt(0);
If you want to get the count of records then you have to apply the group by on some field or apply the below query.
Like
db.rawQuery("select count(field) as count_record from tablename where field =" + condition, null);
Another way would be using:
myCursor.getCount();
on a Cursor like:
Cursor myCursor = db.query(table_Name, new String[] { row_Username },
row_Username + " =? AND " + row_Password + " =?",
new String[] { entered_Password, entered_Password },
null, null, null);
If you can think of getting away from the raw query.
int nombr = 0;
Cursor cursor = sqlDatabase.rawQuery("SELECT column FROM table WHERE column = Value", null);
nombr = cursor.getCount();
I would like to update my SQL lite database with the native update-method of the SQLiteDatabase class of android.
ContentValues dataToInsert = new ContentValues();
dataToInsert.put("name", "flo");
dataToInsert.put("location", "flotown");
String where = "id" + "=" + id;
try{
db.update(DATABASE_TABLE, dataToInsert, where, null);
}
catch (Exception e){
String error = e.getMessage().toString();
}
but I get following error:
android.database.sqlite.SQLiteException: near "15": syntax error: ,
while compiling: UPDATE mytable SET location=?, name=? WHERE
id=2010-09-21 15:05:36.995
I don´t know what should be the problem. Somehow the values do not arrive in the SQL statement. I did nearly the same with the insert method and that worked quite fine.
You're using the update function wrong. It should be like this:
String where = "id=?";
String[] whereArgs = new String[] {String.valueOf(id)};
db.update(DATABASE_TABLE, dataToInsert, where, whereArgs);
The Strings in the whereArgs array gets substituted in for each '?' in the where variable.
ie. if you had where = "name=? AND type=? then the first '?' would get replaced by whereArgs[0] and the second by whereArgs[1].
Actually, you just need to add apostrophes to your where clause. So it ought to be:
String where = "id='" + id + "'"
(note: however, this is not best practice, as it theoretically leaves open to injection attacks)
I have an other approach
public boolean updateEmployee(TalebeDataUser fav) {
SQLiteDatabase database = dbHelper.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(DBHelper.COLUMN_ID, fav.getId());
contentValues.put(DBHelper.COLUM_AD, fav.getAd());
contentValues.put(DBHelper.COLUMN_NUMARA, fav.getNumara());
contentValues.put(DBHelper.COLUMN_YURD_ID, fav.getYurtID());
contentValues.put(DBHelper.COLUMN_EGITIM_ID, fav.getEgitimTur());
contentValues.put(DBHelper.COLUMN_TEL, fav.getTel());
contentValues.put(DBHelper.COLUMN_EMAIL, fav.getEmail());
contentValues.put(DBHelper.COLUMN_ADDRESS, fav.getAdres());
String whereClause = DBHelper.COLUM_AD + " = ? AND " + DBHelper.COLUMN_NUMARA + " = ? ";
final String whereArgs[] = {fav.getAd(), String.valueOf(fav.getNumara())};// old nameler taranıyor
int affectedRows = database.update(DBHelper.TABLE_NAME_OGR, contentValues, whereClause, whereArgs);
return affectedRows > 0;
}
Actually what exactly you written is correct. The syntax is correct.
But you have to check these.
String where = "id" + "=" + id;
In the above declaration "id" should be type number and id should be int.
And if id is a type of TEXT then follow #Adam javin answer.