I am selecting row based on user id but non is returning
select all is working and i am sure of the id in the where
can somone help me what is wrong with the query
String sql = "SELECT * FROM " + TABLE_Txns
+ " WHERE " + COLUMN_USERID + " = ?";
SQLiteDatabase db = this.getReadableDatabase();
List<TransactionModel> savedTransactions = new ArrayList<>();
Cursor cursor = db.rawQuery(sql, null
, new String[]{getLogin_id()});
Use rawQuery() this way:
Cursor cursor = db.rawQuery(sql, new String[]{getLogin_id()});
The 2nd parameter is the selection arguments.
The signature you used with 3 parameters is this:
rawQuery(String sql, String[] selectionArgs, CancellationSignal cancellationSignal)
and you don't need that.
I am developing an app in which suggestive list is displayed as I start typing in SearchView. Everything is going well but as I type in SearchView the App just crashes.
public Cursor searchByBrandText(String inputTextBrand) throws SQLException {
db = this.getReadableDatabase();
String where = inputTextBrand;
String extra = "'%" + where + "%'";
String query = "SELECT Brand_Name" + " from " + "Sample" + " where "
+ "Brand_Name" + " LIKE " + extra;
Cursor mCursor = db.rawQuery(query, null);
if (mCursor.getCount() <= 0) {
mCursor.close();
return null;
} else {
return mCursor;
}
}
' is the SQL string delimiter.
You have to double it, if you need to insert a value containing that character.
Like so:
String where = inputTextBrand.replace("'", "''");
Or, better, use bound parameters (in this case there's no need to double the ').
Like so:
String query = "SELECT Brand_Name FROM Sample WHERE Brand_Name LIKE ?";
Cursor mCursor = db.rawQuery(query, new String[]{"%" + inputTextBrand + "%"});
The single quotation mark is messing up your sql query, this is reasonably serious because as it is somebody could use your text box to carry out an SQL Injection Attack on your database.
The method of dealing with this has been answered here: Android Quotes within an SQL query string
How can I compare column content values? So if content values contain "ted" return all data in cursor.
public Cursor listNotes() {
String username = session.getUser();
String query = "SELECT * FROM Task WHERE " +help.Column_owner+ " = " +username ;
Cursor c = db.rawQuery(query, null);
return c;
}
Here is the error, I am trying to compare username to the content values in the column_create but its not working
no such column: ted (code 1): , while compiling: SELECT * FROM Notes WHERE column_owner = ted
username must be enclosed in apostrophes ('), because it is a string!
Correct your code like this:
String query = "SELECT * FROM Task WHERE " + help.Column_owner + " = '" +username + "'";
Or, better, use a bound parameter (in this case, Android takes care of the apostrophes for you and you're less prone to SQL injection - and, last but not least, you use less string concatenations):
String query = "SELECT * FROM Task WHERE " + help.Column_owner + " = ?";
Cursor c = db.rawQuery(query, new String[]{username});
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.
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();