SQLite no such column error - android

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

Related

Getting a sqlite exception

I am a beginner in SQLite and getting this exception in the highlighted line-
Caused by: android.database.sqlite.SQLiteException: no such table: VocabDatabase (code 1 SQLITE_ERROR): , while compiling: SELECT Word, Meaning FROM VocabDatabase WHERE _id = ?
My MainActivity code -
try {
**strong textCursor cursor = db.query(DatabaseHelper.DB_name, new String[]{"Word", "Meaning"},
"_id = ?", new String[]{Integer.toString(0)}, null, null, null);**
if (cursor.moveToFirst()) {
String word = cursor.getString(0);
String meaning = cursor.getString(0);
TextView tv1 = findViewById(R.id.tv1);
TextView tv2 = findViewById(R.id.tv2);
tv1.setText(word);
tv2.setText(meaning);
}
cursor.close();
db.close();
}catch(SQLException e){
Toast.makeText(this, "Can't access the database", Toast.LENGTH_SHORT).show();
}
SQLite Helper -
public void onCreate(SQLiteDatabase db)
{ db.execSQL("create table Vocabwords (_id integer primary key autoincrement, Word text, Meaning text)");
insertNewEntry(db, "Diabolic","Evil");
insertNewEntry(db,"Concede","Agree to an argument after declaring it incorrect in past");
}
VocabDatabase is a database name, but in SELECT clause, you need a table
name.
Maybe the table name is Vocabwords, please check again.

Select Query issue while fetching the fields

I wrote one query which select the name and designation fields based on id and then in fragment class i am calling that method which belongs to the appropriate query but unfortunately i am getting Sqlite Exception.
Database Method
public Employee getEmployeeName(int id) {
SQLiteDatabase db = this.getWritableDatabase();
Employee employee = new Employee();
String query ="SELECT " + KEY_NAME +", " +KEY_DESIG +" FROM " + TABLE_EMPLOYEES+ " WHERE " + KEY_ID + "=" + id;
Cursor cursor = db.rawQuery(query, null);
if (cursor.moveToFirst()) {
do {
employee.setName(cursor.getString(1));
employee.setDesignation(cursor.getString(2));
} while (cursor.moveToNext());
}
return employee;
}
Calling from the Fragment
db.getEmployeeName(selectedManager);
Exception
01-07 06:02:34.185: E/AndroidRuntime(2386): java.lang.IllegalStateException: Couldn't read row 0, col 2 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
Column indexes are zero-based. getString(2) refers to the third column and your cursor has only two columns.
Change
employee.setName(cursor.getString(1));
employee.setDesignation(cursor.getString(2));
to
employee.setName(cursor.getString(0));
employee.setDesignation(cursor.getString(1));
try this
if (cursor.moveToFirst()) {
do {
employee.setName(cursor.getString(cursor.getColumnIndex(KEY_NAME));
employee.setDesignation(cursor.getString(cursor.getColumnIndex(KEY_DESIG));
} while (cursor.moveToNext());
}
Get data from Cursor by using cursor.getColumnIndex(COLUMN NAME)

How to get execute query string in sqlite for android?

I am using sqlite
i want to print the query executed in db to insert
here is my code
// for SAving Ocean/Air sales
public int saveOrder(Order odr) throws SQLException {
SQLiteDatabase db = con.getWritableDatabase();
int ordrId = 0;
ContentValues values = new ContentValues();
values.put("cr_usr", odr.getCrUsr());
values.put("cr_ts", odr.getCrTs().toString());
values.put("eat_mst_cust_id", odr.getEatMstCustId());
values.put("ordr_dt", odr.getOrdrDt().toString());
String selectQuery = "SELECT last_insert_rowid()";
try {
// Inserting Row
db.insertOrThrow("eat_ordr", null, values);---getting error here for constraint failed
Cursor cursor = db.rawQuery(selectQuery, null);
cursor.moveToFirst();
ordrId = cursor.getInt(0);
db.close();
} finally {
db.close();
}
return ordrId;
}
I am not getting any error but row is failed to insert bcz it returns 0 for idvalue
so i want to see executed query how to get that query?
here is my table structure
CREATE TABLE "eat_ordr" ("eat_ordr_id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL ,
"eat_mst_cust_id" VARCHAR NOT NULL REFERENCES "eat_mst_cust"("eat_mst_cust_id"),
"ordr_no" VARCHAR NOT NULL UNIQUE ,
"ordr_dt" DATETIME NOT NULL ,
"ordr_stat" VARCHAR NOT NULL ,
"last_sync_ts" DATETIME,
"cr_ts" DATETIME DEFAULT CURRENT_TIMESTAMP, "md_ts" DATETIME, "cr_usr" VARCHAR, "md_usr" VARCHAR)
The insertOrThrow documentation says:
Returns
the row ID of the newly inserted row
So this can be done much easier:
ordrId = db.insertOrThrow("eat_ordr", null, values);

data cant be inserted to the sqlit database tables

I am trying to insert data in my sqlit database but I got android SQLiteConstraintException: error code 19: constraint failed exception. I saw there are tons of question in this topic, I've read and tried a bunch of them, but the exception still , i wonder if this exception caused by the auto increment food_id value , since the insert statement return -1 , and i wonder that why this exception occur since the first insert id done correctly but all the later inserting are failed , why this error occur ,and how i can solve it? please help me..
the create statements in the DBAdapter class
private static final String Meal_TABLE_CREATE= "create table IF NOT EXISTS Meal (Date text not null , "+
"Time text not null,MealType text not null,"+ " primary key(Date,Time ,MealType) );" ;
private static final String FOOD_TABLE_CREATE= "create table IF NOT EXISTS Food (_id INTEGER primary key AUTOINCREMENT , "+
"Food_Name text not null,Calories integer not null,"+ "VB12 integer not null,Cholesterol integer not null,"+
"Protein integer not null,Iron integer not null,Sodium integer not null,Fat_Mono integer not null,Fat_Sat integer not null,carbohydrate integer not null);" ;
private static final String MealFOOD_TABLE_CREATE= "create table IF NOT EXISTS MealFood (Date text not null , "+
"Time text not null,MealType text not null,"+"Food_ID integer not null , primary key(Date,Time ,MealType,Food_ID) );" ;
inserting methods
// insert meal to the meal table
public long SaveMeal(String date , String time , String mealType)
{
ContentValues content = new ContentValues();
content.put(KEY_MDATE,date);
content.put(KEY_MTIME,time);
content.put(KEY_MEALTYPE,mealType);
return db.insert(MEAL_TABLE_NAME, null, content);
}
// insert Food to the Food table
public long SaveFood(String name,int calories,int Vit_B12,int cholesterol,int protein ,int iron ,int sodium,int Fat_Mono,int Fat_Sat,int carbohydrate)
{
ContentValues content = new ContentValues();
content.put(KEY_FOODNAME,name);
content.put(KEY_CALORIES,calories);
content.put(KEY_VB12,Vit_B12);
content.put(KEY_CHOLESTEROL,cholesterol);
content.put(KEY_PROTEIN,protein);
content.put(KEY_IRON,iron);
content.put(KEY_SODIUM,sodium);
content.put(KEY_FAT_MONO,Fat_Mono);
content.put(KEY_FAT_Sat,Fat_Sat);
content.put(KEY_CARBOHYDRATE,carbohydrate);
return db.insert(FOOD_TABLE_NAME, null, content);
}
// get food id by its name
public int getFoodIDByName(String name) throws SQLException
{ int id;
Cursor cursor = null;
try{
cursor=db.query(true,FOOD_TABLE_NAME, new String[]{KEY_FOODID}, KEY_FOODNAME+ " = '" + name + "'", null, null, null, null,null);
if (cursor != null) {
cursor.moveToFirst();
}
id=0;
while (cursor.moveToNext())
id=cursor.getInt(cursor.getColumnIndex(KEY_FOODID));
}
finally{
cursor.close();
cursor.deactivate();
}
return id;
}
// insert mealFood to mealFood table
public long SaveMealFood(String date , String time , String mealType, int Food_id)
{
ContentValues content = new ContentValues();
content.put(KEY_MFDATE,date);
content.put(KEY_MFTIME,time);
content.put(KEY_MFMEALTYPE,mealType);
content.put(KEY_MFFOODID,Food_id);
return db.insert(MEALFOOD_TABLE_NAME, null, content);
}
java code
DBAdapter dbAdapter=new DBAdapter(SaveMeal.this);
dbAdapter.open();
Food n;
String m;
int FoodIDByName;
for(int i = 0; i <MealActivity.array.size(); i++){
m=MealActivity.array.get(i).toString();
Log.e("tag", m);//selected food name
for (int j = 0; j < MealActivity.tempList.size(); j++){
n=MealActivity.tempList.get(j);
if(n.getFOOD_NAME().equals(m)){
//save food
long food_id = dbAdapter.SaveFood(n.getFOOD_NAME(),n.getCALORIES(),n.getFOOD_VITAMIN_B12(),n.getCHOLESTEROL(),n.getFOOD_PROTEIN(),n.getFOOD_IRON(),n.getFOOD_SODIUM(),
n.getFOOD_MONO_UNSATURATED_FAT(),n.getFOOD_SATURATED_FAT(),n.getFOOD_TOTAL_CARBOHYDRATE());
Log.e("tag", food_id+" food inserting done");
//save meal
long meal_id= dbAdapter.SaveMeal( meal_date,meal_time,Meal.MEAL_TYPE);
Log.e("tag",meal_id+" meal inserting done");
//save meal_food
FoodIDByName=dbAdapter.getFoodIDByName(n.FOOD_NAME);
Log.e("tag",FoodIDByName+" food_id");
long meal_food_id=dbAdapter.SaveMealFood(meal_date,meal_time,Meal.MEAL_TYPE,FoodIDByName);
Log.e("tag",meal_food_id+" meal_food inserting done");
dbAdapter.close();
this result of this line Log.e("tag", food_id+" food inserting done"); in my log is -1
mylog
Database(657):at android.database.sqlite.SQLiteStatement.native_execute(Native Method)
Database(657):at android.database.sqlite.SQLiteStatement.execute (SQLiteStatement.java:55)
Database(657):at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1410)
-1 food inserting done
18 meal inserting done
0 food_id
13 meal_food inserting done
Try to remove all (Not NULL) constraints, and save the empty food.
If it is saved properly, try to add the constraint (NOT NULL) one by one.
I think one of the values is passed as NULL.
That error.means you are.violating a constraint (obviously). Most likely leave a "not null" column null.
You could also have violated your primary key by trying to save the same combination more than once.

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

Categories

Resources