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.
Related
I have a query that joins 2 tables get the required data on my android, what picture here is the user clicks on an item and the item's ID is used to query the right data in the Database, I know I can simply use database.query() but it according to my research it is used for simply database querying only, in my case I should use rawQuery() which provides more power of the database. below is my query which links table 1 to table 2 to get the users name from table one and user last name from table 2 if the foreign key is the same as user key
Assume this is my query:
String sQuery = SELECT table1.ID, table2.userlastname FROM table1, table2 WHERE "+table1.ID = table2.foreign;
If i try to specify the user id like below it gets all data in the database table which means i should replace id with "=?" but how do I do this when I am dealing which such a query, one that uses db.rawQuery() instead of db.query()
`private Object userInfo(int id)
{
String sQuery = SELECT table1.ID, table2.userlastname
FROM table1, table2 WHERE "+table1.ID = id;
}`
Basically you replace the parameter by question marks '?' and pass them through a String array in the order they appear in the query.
String queryStr = "SELECT table1.ID, table2.userlastname
FROM table1
INNER JOIN table2 ON table1.ID = table2.foreign;
WHERE table1.ID = ?";
String[] args = new String[1];
args[0] = String.valueOf(id);
Cursor cur = db.rawQuery(queryStr, args);
it did not work until I joined table 2 like:
`String queryStr = "SELECT table1.ID, table2.userlastname
FROM table1
INNER JOIN table2 ON table1.ID = table2.foreign
WHERE table1.ID = ?";
String[] args = new String[1];
args[0] = String.valueOf(id);
Cursor cur = db.rawQuery(queryStr, args);`
I'm trying a simple SQL Command wihtin my Android-App, to get the age of a selected Person:
public int getAge(){
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM persons WHERE name =? " + MainActivity.selectedPerson.getText().toString(), null);
int age = cursor.getInt(3); // column with ages
cursor.close();
db.close();
return age;
}
But when I run my app, it crashes when I call the function getAge(). I get the following Error:
SQLiteException: no such column: Max: , while compiling: SELECT * FROM persons WHERE name = Max
I don't get it. There is the name "Max" in the table. What am I doing wrong? Thanks in advance.
Edit 2:
With this one:
Cursor cursor = db.rawQuery("SELECT name FROM persons WHERE name = '" + MainActivity.selectedPerson.getText().toString() + "'", null);
I get a different error:
08-27 19:43:47.573: E/AndroidRuntime(6161): android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 1
what does this mean?
You should consider using the selectionArgs parameter of rawQuery() to prevent SQL Injection Attacks:
Cursor cursor = db.rawQuery("SELECT * FROM persons WHERE name = ?", new String[] { MainActivity.selectedPerson.getText().toString() });
Also you only need one column so rather than wasting resources by selecting them all with *, you should just select the one column:
Cursor cursor = db.rawQuery("SELECT age FROM persons WHERE name = ?", new String[] { MainActivity.selectedPerson.getText().toString() });
Hope that helps!
All together it should look like:
public int getAge(){
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT age FROM persons WHERE name = ?", new String[] { MainActivity.selectedPerson.getText().toString() });
int age;
// Check if you have a valid result and move to the first row to read it
if(cursor.moveToFirst())
age = cursor.getInt(0);
// Prevent a crash if there is no data for this name
else
age = 0;
cursor.close();
db.close();
return age;
}
Chan ge the 3rd line of your program:
Cursor cursor = db.rawQuery("SELECT * FROM persons WHERE name =? " + MainActivity.selectedPerson.getText().toString(), null);
to this:
Cursor cursor = db.rawQuery("SELECT * FROM persons WHERE name = ?", new String[] { MainActivity.selectedPerson.getText().toString()} );
Try this:
public int getAge(){
int age;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM persons WHERE name = '" + MainActivity.selectedPerson.getText().toString()+"'",null);
if(cursor.moveToFirst())
{
age = cursor.getInt(3); // column with ages
}
cursor.close();
db.close();
return age;
}
You missed the single quotes (' ') in your sql command. That's why MAX was taken as a column and not as a value.
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
I have an Android app that has a database. My database has a table say Person Table, which has 4 columns , Firstname, lastname, DOB and Age. How do I go about retrieving just the DOB information for all the rows in the table.
Your help would be most appreciated.
When querying, just specify the columns that you're after:
DatabaseHelper dbHelper = new DatabaseHelper(this);
SQLiteDatabase db = dbHelper.getReadableDatabase();
String[] cols = {"dob"};
Cursor result = db.query("person", cols, null, null, null, null, null);
List<String> DobList = new ArrayList<String>();
Cursor cursor = db.rawQuery(String.format("select DOB from %s", TABLE_NAME);
if (cursor.movetoFirst) {
do {
DobList.add(cursor.getString(cursor.getColumnIndex("DOB")));
} while (cursor.moveToNext());
}
cursor.close();
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.