I have 2 tables i SQLite working with Android.
Table 1 = T1
_id = INTEGER PRIMARY KEY AUTOINCREMENT
name = TEXT NOT NULL
time = TEXT NOT NULL
Table 2 = T2
_id = INTEGER PRIMARY KEY AUTOINCREMENT
ref = TEXT NOT NULL
info = TEXT NOT NULL
IN QUERY This is a list from T1 and works fine
String orderBy = DBhelper.time + " ASC";
String[] columns = new String[]{ DBhelper._id, DBhelper.name, DBhelper.time};
Cursor c = db.query(true, DBhelper.T1, columns, null, null, null, null, orderBy, null, null);
Now I want to add in a lookup to table 2 in the query, like old fashioned:
SELECT T1._id, T1.name, T1.time, T2.info FROM T1, T2 WHERE T2.ref = T1._id;
Mind you: T1._id is integer and T2.ref is string.
Can anyone help me to do this?
When you're starting with a raw SQL query, the easiest way to use it is with rawQuery:
String sql = "SELECT T1._id, T1.name, T1.time, T2.info FROM T1 JOIN T2 ON T2.ref = T1._id";
Cursor c = db.rawQuery(sql, null);
The not-so-easy way would be to use SQLiteQueryBuilder, but this is useful mostly for content providers that need to safely handle SQL snippets from potentially malicious third party apps.
Related
I have 2 tables naming labels5,labels.
i would like to compare the difference between this two column data and display.
same like below i need it in sqlite query.
current codings.
public Cursor getLotsPerCustomer1(long name) {
SQLiteDatabase db = this.getReadableDatabase();
String whereclause = KEY_NAME + "=?";
String[] whereargs = new String[] {
String.valueOf(name)
};
return db.query(TABLE_LABELS, null, whereclause, whereargs, null, null, ROUTE);
}
i want same as below in sqlite format. please advise.
select t1.route from labels t1
left
join labels5 t2 on t1.route = t2.number
where t2.number is null
There is two condition is involved.
First condition is check the table "customer" and search the matching result from table labels which is working fine this query.
public Cursor getLotsPerCustomer1(long name) {
SQLiteDatabase db = this.getReadableDatabase();
String whereclause = KEY_NAME + "=?";
String[] whereargs = new String[] {
String.valueOf(name)
};
return db.query(TABLE_LABELS, null, whereclause, whereargs, null, null, ROUTE);
}
Second condition is ,
After passing the first condition then it should also compare with table "labels5" thats where i struck .Appreciate your advise.
TABLE CUSTOMER:
CREATE TABLE "customer" (
"_id"
TEXT,
"customer_name"
TEXT
);
TABLE LABELS
CREATE TABLE "labels" (
"sno" INTEGER,
"route" TEXT,
"id" TEXT,
"_id" TEXT
);
TABLE LABELS5
CREATE TABLE "labels5" (
"id3" INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,
"number" TEXT NOT NULL UNIQUE,
"outletname" TEXT,
"sunday" INTEGER,
"monday" INTEGER,
"tuesday" INTEGER,
"wednesday" INTEGER,
"thursday" INTEGER,
"saturday" INTEGER,
"closed" INTEGER,
"calling" TEXT,
"week" INTEGER
);
You can do it with rawQuery():
public Cursor getRoutes(long name) {
SQLiteDatabase db = this.getReadableDatabase();
String sql = "select t1.route from labels t1 left join labels5 t2 on t1.route = t2.number where t2.number is null";
return db.rawQuery(sql, null);
}
A better way to get the values from one table that aren't in another is to use EXCEPT:
SELECT route FROM labels
EXCEPT
SELECT number FROM labels5;
select customer_name as FirstTable,route as SecondTale,number as ThirdTable
from customer,labels,labels5
where customer._id=labels._id AND labels.route=labels5.number
i want to filter multiple data such as
id = "1,3,5" from columnid which is having 1 to 10 id
and another column such as name
name = "a,e,d" from name column of 10 records
and another criteria such as age
age = "21,23,20" from age column of 10 records from same table,
one example i got is
Cursor cursor = db.query("TABLE_NAME",new String[]{"ColumnName"}, "ColumnName=?",new String[]{"value"}, null, null, null);
which is just for one column but i want to get data from multiple column, can anyone help me?
try this working example,
Cursor cursor =
db.query(TABLE_DIARYENTRIES,
new String[] {},
STUDENT_ID + " IN ("+resultStudent+")"+ " AND " +CLASS_NAME + " IN ("+resultClass+")"
+ " AND " +SUBJECT_NAME + " IN ("+resultSubject+")"
null, null, null, null);
and your result string should be 'a','b','c'
I really like the way Google's example is structured. Because for noobies such as myself it makes it really clear what I am doing. And it is also more robust to SQL injections. Here is my modified version of the Google example:
//Column(s) I want returned
String[] projection = {"ColumnIWantReturned"};
//Column(s) I want to filer on
String selection = "FilterColumn1 IN (?) and FilterColumn2 IN (?, ?)";
String[] selectionArgs = {"ArgumentForFilterColumn1", "FirstArgumentForFilterColumn2", "SecondArgumentForFilterColumn2"};
Cursor cursor = db.query(
"MyTable", // The table to query
projection, // The array of columns to return (pass null to get all)
selection, // The columns for the WHERE clause
selectionArgs, // The values for the WHERE clause
null, // don't group the rows
null, // don't filter by row groups
null // The sort order
);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Log.d("this-is-a-test", cursor.getString(0));
cursor.moveToNext();
}
cursor.close();
I'm making an Android app and using a SQLite database. In particular I'm using the rawQuery method on a database obtained through a SQLiteOpenHelper. The query I build makes use of the ? marks as placeholders for the real values, which are passed along as an array of objects (e.g., select * from table where id = ?).
The question is, is it possible to get the query with the marks already replaced, at least from the cursor returned from the rawQuery method? I mean something like select * from table where id = 56. This would be useful for debugging purposes.
It's not possible. The ? values are not bound at the SQL level but deeper, and there's no "result" SQL after binding the values.
Variable binding is a part of the sqlite3 C API, and the Android SQLite APIs just provide a thin wrapper on top. http://sqlite.org/c3ref/bind_blob.html
For debugging purposes you can log your SQL with the ?, and log the values of your bind arguments.
You could form it as a string like this
int id = 56;
String query = "select * from table where id = '" + id + "'";
and then use it as a rawQuery like this (if I understood your question properly)
Cursor mCursor = mDb.rawQuery(query, null);
You can also use the SQLiteQueryBuilder. Here is an example with a join query:
//Create new querybuilder
SQLiteQueryBuilder _QB = new SQLiteQueryBuilder();
//Specify books table and add join to categories table (use full_id for joining categories table)
_QB.setTables(BookColumns.TABLENAME +
" LEFT OUTER JOIN " + CategoryColumns.TABLENAME + " ON " +
BookColumns.CATEGORY + " = " + CategoryColumns.FULL_ID);
//Order by records by title
_OrderBy = BookColumns.BOOK_TITLE + " ASC";
//Open database connection
SQLiteDatabase _DB = fDatabaseHelper.getReadableDatabase();
//Get cursor
Cursor _Result = _QB.query(_DB, null, null, null, null, null, _OrderBy);
what do you think my problem is.
I am querying a sqlite database.
This code doesn't give any result.
String sql = " select _id from MYTABLE where _id = ? ";
Cursor cur = mDb.rawQuery(sql, new String[] {"5653"}) ;
but if I am executing the query without parameters like this:
String sql = " select _id from MYTABLE where _id = 5653 ";
Cursor cur = mDb.rawQuery(sql, null) ;
One row is returned as expected.
Many thanks.
That happens because the values are bound as strings, and that column is (i am guessing) an int. so the where clause will end up being
where _id = "5653"
From rawQuery javadoc for selectionArgs -
You may include ?s in where clause in the query, which will be replaced by the values from selectionArgs. The values will be bound as Strings.
Try this:
String sql = " select _id from MYTABLE where _id = '5653' ";
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();