Home > Net >  Can't insert Data on SQLite Database Android
Can't insert Data on SQLite Database Android

Time:10-27

I have tried to insert Student Dethasails on my Student Table Data. But this error is shown: Error inserting STUDENT_ROLL=1 STUDENT_NAME=D _CID=4 android.database.sqlite.SQLiteException: no such table: STUDENT_TABLE (code 1): , while compiling: INSERT INTO STUDENT_TABLE(STUDENT_ROLL,STUDENT_NAME,_CID) VALUES (?,?,?)

This is my code: Declare Table:-

public static final String STUDENT_TABLE_NAME = "STUDENT_TABLE";
public static final String S_ID = "_SID";
public static final String STUDENT_NAME_KEY = "STUDENT_NAME";
public static final String STUDENT_ROLL_KEY = "STUDENT_ROLL";

public static final String CREATE_STUDENT_TABLE = 
        "CREATE TABLE "   STUDENT_TABLE_NAME   "("  
                S_ID   " INTEGER PRIMARY KEY AUTOINCREMENT, "  
                C_ID   " LONG , "  
                STUDENT_NAME_KEY   " VARCHAR(255), "  
                STUDENT_ROLL_KEY   " INTEGER , "  
                " FOREIGN KEY ("   C_ID   ") REFERENCES "   CLASS_TABLE_NAME   "("  C_ID ")"  ");";

public static final String DROP_STUDENT_TABLE = " DROP TABLE IF EXISTS "   STUDENT_TABLE_NAME;
public static final String SELECT_STUDENT_TABLE = "SELECT * FROM "   STUDENT_TABLE_NAME;

Add Student Method for adding Students. c_id is a foreign key.

long addStudent(long c_id, String studentName, int studentRoll){
    SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
    ContentValues values = new ContentValues();
    values.put(STUDENT_NAME_KEY,studentName);
    values.put(STUDENT_ROLL_KEY,studentRoll);
    values.put(C_ID, c_id);
    try{
        long s_id = sqLiteDatabase.insert(STUDENT_TABLE_NAME, null, values);
        return s_id;
    } catch (SQLException e){
        e.printStackTrace();
    }
    return -1;
}

CodePudding user response:

The problem here as indicated in the logs is that the table doesn't exists. You created the sqlite statement for creation of the table but I think you didn't execute it from anywhere. You must execute the sqlite statement in your Database helper class:

@Override
public void onCreate(SQLiteDatabase database) {
  database.execSQL(CREATE_STUDENT_TABLE);
}

More information can be found here

CodePudding user response:

you created the query to create your table but it has not been executed anywhere, you just have to execute it before performing an insert

  database.execSQL(CREATE_STUDENT_TABLE);
  • Related