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
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 have in my database this table Cast with columns ID and Actor for example
ID | Actor
----+------
123 | Michael Douglas
123 | Robert Duval
I would like to return columns ID and Cast in my cursor for a specific ID
public Cursor getCastCursor(String ID){
SQLiteDatabase db = getReadableDatabase();
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
String[] sqlSelect = new String[]{"ID","Actor"};
String[] selectionArg = new String[]{ID};
qb.setTables("Cast");
Cursor c = qb.query(
db, //SQLiteDatabase db
sqlSelect, //String[] projectionIn
"ID=?", //String selection
selectionArg, //String[] selectionArgs
null, //String groupBy
null, //String having
null); //String sortOrder
c.moveToFirst();
return c;
}
I keep getting this error, and sure why
no such table: Cast (code 1): , while compiling: SELECT ID, Actor FROM Cast WHERE (ID=?)
edit
Here is a picture of my database. Clearly the table exists.
I create the database using Python
#Add countries, genres, directors, and actors tables
def createTables(source):
with sqlite3.connect(source) as connection:
c = connection.cursor()
c.execute("""Select * from Movies""")
all_data = c.fetchall()
c.execute("""CREATE TABLE IF NOT EXISTS Countries(ID TEXT,Country TEXT)""")
c.execute("""CREATE TABLE IF NOT EXISTS Actors(ID TEXT, Actor TEXT)""")
c.execute("""CREATE TABLE IF NOT EXISTS Genres(ID TEXT,Genre TEXT)""")
c.execute("""CREATE TABLE IF NOT EXISTS Directors(ID TEXT,Director TEXT)""")
for single_data in all_data:
countries = returnCommaDelimitedList(single_data[18])
directors = returnCommaDelimitedList(single_data[8])
genres = returnCommaDelimitedList(single_data[6])
actors = returnCommaDelimitedList(single_data[10])
for single_actor in actors:
c.execute("INSERT INTO Actors VALUES(?,?);",(single_data[0],single_actor))
for single_country in countries:
c.execute("INSERT INTO Countries VALUES(?,?);",(single_data[0],single_country))
for single_director in directors:
c.execute("INSERT INTO Directors VALUES(?,?);",(single_data[0],single_director))
for single_genre in genres:
c.execute("INSERT INTO Genres VALUES(?,?);",(single_data[0],single_genre))
So I cleaned, rebuilt, and remade my project and then uninstalled and reinstalled the app and that did the trick.
Hi can anyone please help me with below error in android sqlite ? really appreciate!
Caused by: android.database.sqlite.SQLiteException: no such column: House (code 1): , while compiling: select * from category where category =House
below is part of my code in which I have inserted "House" in the table
public void onCreate(SQLiteDatabase db) {
String CREATE_CATEGORY_TABLE = "CREATE TABLE category( " +
"_id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"category TEXT UNIQUE)";
db.execSQL(CREATE_CATEGORY_TABLE);
}
public void addCategory(String name){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("category", name);
db.insert(CATEGORY_TABLE, // table
null, //nullColumnHack
cv); // key/value -> keys = column names/ values = column values
db.close();}
public List getCategory(){
List<String> list=new LinkedList();
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor =
db.rawQuery("select * from category where category =house" , null);
// 3. if we got results get the first one
if (cursor != null)
cursor.moveToFirst();
do {
String s = (cursor.getString(1));
list.add(s);
}while (cursor.moveToNext());
return list;
}
You need to wrap house with single quotes
db.rawQuery("select * from category where category = 'house'" , null);
In my case error was in trigger I wrote on table insert and update
I am developing my first application which contains an SQLite database, containing table ANIMAL which has the columns _id, animal_name, animal_bio.
The user is presented with animal names in a ListView; selecting an animal will bring him/her to a page where he/she can view the animals bio.
The problem I'm having is:
When I add the bio of each animal to the DB - no errors.
However, running the app causes the ListView (previously working) to display a blank screen.
My Insertion code:
public long populateDB(){
ContentValues initialValues = new ContentValues();
long[] rowIds = new long[animalName.length];
// Populate the animal table
for(int i = 0; i < animalName.length; i++){
initialValues.put(KEY_ANIMALNAME, animalName[i]);
initialValues.put(KEY_BIOGRAPHY, bio[i]);
rowIds[i] = qmDB.insert(ANIMAL_TABLE, null, initialValues);
}
return rowIds[0];
}
And the create database statement
private static final String DATABASE_CREATE =
"create table " + ANIMAL_TABLE +
" (_id integer primary key autoincrement, " +
"animal_name text not null, " +
"biography text not null);";
I cannot see anything wrong with this code, so if anyone has any suggestions, I'd be very grateful.
EDIT: Retrieving animals code
public Cursor retrieveAnnimals(){
return qmDB.query(ANIMAL_TABLE, new String[] {
KEY_ROWID,
KEY_ANIMALNAME,
},
null,
null,
null,
null,
ORDER_BY_NAME);
}
Calling the create and insert from application, this takes place in the ListActivity, called ListAnimals:
dbm = new MyDBManager();
dbm.open();
dbm.deleteTable();
dbm.populateTable();
myCursor = dbm.retrieveAnimals();
Hi all
I create a table like that
private static final String CREATE_TABLE_PRODUCT =
"create table prod (id integer primary key,titre text not null, desc text, is_free integer);";
i update it this way
SQLiteDatabase db = getConnection();
ContentValues updateEvent = new ContentValues();
updateEvent.put("is_free", 1);
int ok = db.update(prod, updateEvent, "id=?",
new String[] { Long.toString(evenement.getId()) });
db.close();
I do see the change in eclipse with DDMS questoid
but when i try to retrieve the value I get nothing ....
Cursor c = db.query(prod, new String[] { "id",
"titre", "desc", "is_free", },
"is_free=?", new String[] {"1"}, null, null,
null);
I've tried some variant like
String query = "SELECT * FROM "+EVENEMENT_TABLE+" WHERE is_free=1;";
Cursor c = sdb.rawQuery(query, null);
with no success
is this problem come from the type (integer) of my column ?
Any help
Do not use reserved keywords like desc in your queries. This probably causes query to fail.
In case you don't know update will not add values to the table. Use insert instead.