SQLITE: Display difference between three table difference with two condition - android

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

Related

SQLite query 2 tables into android cursor

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.

how to check if a value already exist in db, and if so how to get the id of that row? android sql

i have created the next db file -
String sql = ""
+ "CREATE TABLE "+ Constants.TABLE_NAME + " ("
+ Constants.NAME_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ Constants.NAME_PERSON + " TEXT"
+ ")";
db.execSQL(sql);
Now what I would like to know is, how to be able to run on the db and to know if a name already exist sin the db, and if so i would like to get the id of that row.
all i can understand is that i should use the
Cursor c= db.query(table, columns, selection, selectionArgs, groupBy, having, orderBy)
but I don't have a clue what I should do next -
so thanks for any kind of help
you can add this in your DB and call the function passing "to be searched key" as an argument
public boolean checkIfExist(String name) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_INFO, new String[] { KEY_TITLE}, KEY_TITLE + "=?",
new String[] { name }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
if (cursor.moveToFirst()) {
return true;
}else{
return false;
}
}
Where KEY_TITLE is the column name in your table.
Take more example on this:
AndroidSQLite
AndroidSQLite with multi tables
Make a SELECT request. Then check with if(cursor.moveToFirst()) if your name is already existing. (moveToFirst() return true if there is at least 1 value).
So if your value is existing, juste get its id with cursor.getString(cursor.getColumnIndex("_id"));

get dat from cursor to arraylist

I have a table with 10 columns.
String createQuery = " CREATE TABLE IF NOT EXISTS profile (
_id integer primary key autoincrement,
name text,
longi real,
lati real,
vibration integer,
sound integer,
brightness integer,
mdata,
bluetooth,
wifi);";
How can I get all table data in an ArrayList?
You need to do a few things. You need to create a sub-class of SQLiteDatabase. Once you have that, you can get run a query inside a method in this class like this:
Cursor cursor = getReadableDatabase().query("profile", // table name
new String[] { // columns
"_id",
"name",
"longi",
"lati",
"vibration",
"sound",
"brightness",
"mdata",
"bluetooth",
"wifi"
},
null, null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Long id = cursor.getLong("_id");
String name = cursor.getString("name");
// and so on, list of your columns you want to get.
cursor.moveToNext();
}
Obviously you won't be able to put one whole row into an array list because you have different column types. But you can process one row at a time inside the while loop after you get all the values.
Most of this info is taken from here, which is a great source of info:
http://www.vogella.com/articles/AndroidSQLite/article.html

how to fetch data from more than one table

I am new in android development.
I store a list of albums in a table that has these columns: albumid, albumname.
The song table has these columns: songid,song_title,tracksong_id, where the tracksong_id is a foreign key that refers to the albumid.
My create table query for the song table is:
create table album(id integer primary key autoincrement,album_name text)
create table song(song_id integer primary key autoincrement,song_name text not null,song_title text not null,tracksong_id integer,tracksong_id integer,FOREIGN KEY(tracksong_id) REFERENCES album(album_id))
For fetching all song details
public AlbumDTO getSOngById(long id)
{
AlbumDTO occasionDTO=null;
Cursor c=db.query(DATABASE_TABLE_SONG, new String[]
{KEY_SONG_NAME,KEY_SONG_TITEL,TRACKSONGID},TRACKSONGID+"="+id,null,null,null,null);
if(c.moveToNext())
{
occasionDTO=new AlbumDTO();
//occasionDTO.song_id=c.getLong(c.getColumnIndex(KEY_SONG_ID));
occasionDTO.song_name=c.getString(c.getColumnIndex(KEY_SONG_NAME)).trim();
occasionDTO.song_title=c.getString(c.getColumnIndex(KEY_SONG_TITEL)).trim();
occasionDTO.tracksong_id=c.getLong(c.getColumnIndex(TRACKSONGID));
}
close();
return occasionDTO;
}
How can I fetch all data from both tables? One album can contain many songs.
Thanks for support
Alright, this is what you want:
public static final String TABLE_SONG_JOIN_ALBUM = "song LEFT JOIN album ON sone. tracksong_id = album.id";
public static final String[] PROJECTION = new String[] {
"song.song_name",
"album.album_name"
// maybe you want more field here
};
public AlbumDTO getSOngById(long id) {
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
qb.setTables(TABLE_SONG_JOIN_ALBUM);
String selection = "song.id = "+id;
SQLiteDatabase db = dbHelper.getReadableDatabase();
Cursor c = qb.query(db, PROJECTION, selection, null, null, null, sortOrder, null);
AlbumDTO occasionDTO=null;
if(c.moveToNext()) {
occasionDTO=new AlbumDTO();
occasionDTO.song_id=c.getLong(c.getColumnIndex(KEY_SONG_ID));
occasionDTO.song_name=c.getString(c.getColumnIndex(KEY_SONG_NAME)).trim();
occasionDTO.song_title=c.getString(c.getColumnIndex(KEY_SONG_TITEL)).trim();
occasionDTO.tracksong_id=c.getLong(c.getColumnIndex(TRACKSONGID));
}
db.close();
return occasionDTO;
}
table 1
col1 col2 col3
table 2
col1 col2 col3
if we want to select the one one column from both table then the following query is useful
"select a1.col1, a2.col1 from table1 a1, table2 a2 where ;"
here a1 and a2 are alias

SQLite Query in Android to count rows

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();

Categories

Resources