Can't insert Data on SQLite Database Android - java

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;
}

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

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

Java, SQLite, Insert data to Database

I have a SQLite database, with these parameters
private static final String TABLE_NAME = "people_table";
private static final String COL1 = "ID";
private static final String COL2 = "name";
private static final String COL3 = "anything";
Here's how it's created:
String createTable = "CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, " +
COL2 +" TEXT, " + COL3 + "TEXT)" ;
I'm trying to add data to the db, for both columns, my code is here:
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL2, "item");
contentValues.put(COL3, "item2");
long result = db.insert(TABLE_NAME,null,contentValues);
if (result > 0) {
return true;
} else {
return false;
}
But it is not working, I have no idea why.
Please, any advice?
Your issue is that you have omitted a space so there is no column named anything, but instead a column named anythingTEXT
Change to use :-
String createTable = "CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, " +
COL2 +" TEXT, " + COL3 + " TEXT)" ;
Then delete the App's data, or uninstall the App and rerun.
This is required as the onCreate method only runs when the database is first created.

Foreign key in SQLite

I am creating two tables, one for books and one for stores.I want to link every Book in BookStore Table to StoreTable by giving it a Store_ID.
That Store_Id will be the primary key in StoreTable.I am having trouble with the syntax of the foreign key.I also checked http://www.sqlite.org/foreignkeys.html for reference but that didn't provide me with enough clarification.I would be much obliged if anyone helps me.
public class DatabaseHelper extends SQLiteOpenHelper{
//Name of databases
public static final String DATABASE_NAME = "Library.db";
//Version of database
public static final int DATABASE_VERSION = 1;
//Table of Stores
public static final String STORE_TABLE = "Store_Table";
public static final String STORE_ID = "Store_ID";
public static final String STORE_NAME = "Store_name";
public static final String STORE_Address = "Store_Address";
public static final String STORE_LAT = "lat";
public static final String STORE_LNG = "lng";
//Table of Books
public static final String BOOKS_TABLE = "Books_Table";
public static final String BOOK_ID = "Book_ID";
public static final String BOOK_NAME = "Book_name";
public static final String BOOK_AUTHOR = "Book_Author";
public static final String BOOKStore = "BookStore_ID";
//Creating Stores Table
private static final String SQL_CREATE_TABLE_STORE = "CREATE TABLE " + STORE_TABLE + "("
+ STORE_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ STORE_NAME + " TEXT NOT NULL, "
+ STORE_Address + " TEXT NOT NULL, "
+ STORE_LAT + " TEXT NOT NULL, "
+ STORE_LNG + " TEXT NOT NULL"
+");";
//Creating Books Table
private static final String SQL_CREATE_TABLE_BOOKS = "CREATE TABLE " + BOOKS_TABLE + "("
+ BOOK_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ BOOK_NAME + " TEXT NOT NULL, "
+ BOOK_AUTHOR + " TEXT NOT NULL, "
//How to relate BookStore with Store_ID here?
+FOREIGN KEY(BOOKStore) REFERENCES STORE_TABLE(STORE_ID));
+");";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
SQLiteDatabase db = this.getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL(SQL_CREATE_TABLE_STORE);
sqLiteDatabase.execSQL(SQL_CREATE_TABLE_BOOKS);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
//Clear all data
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + STORE_TABLE);
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + BOOKS_TABLE);
//RECREAT THE TABLES
onCreate(sqLiteDatabase);
}
}
I see multiple problems with the CREATE TABLE statement for the Books_Table. First, if you want to designate a column in a table as a foreign key, that column first has to exist. You were referring to the BookStore_ID column when defining your foreign key, but you never actually defined this column. Second, if you want to mark a column as a foreign key, there is a specific syntax. See below for details.
CREATE TABLE Books_Table (
Book_ID INTEGER PRIMARY KEY AUTOINCREMENT,
Book_name TEXT NOT NULL,
Book_Author TEXT NOT NULL,
BookStore_ID INTEGER,
CONSTRAINT fk_bookstore FOREIGN KEY (BookStore_ID)
REFERENCES Store_Table(Store_ID)
);
This is the correct answer:
private static final String SQL_CREATE_TABLE_BOOKS = "CREATE TABLE " + BOOKS_TABLE + "("
+ BOOK_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ BOOK_NAME + " TEXT NOT NULL, "
+ BOOK_AUTHOR + " TEXT NOT NULL, "
//How to relate BookStore with Store_ID here?
+ " FOREIGN KEY ("+ BOOKStore +") REFERENCES "+STORE_TABLE+"("+STORE_ID+"));";

Using SQLite in Android to get RowID

I am creating an app to record assignments for different classes. Each class has it's own unique ID so the assignments listed for each class don't overlap into other classes. Here is a method I made to find the rowid for a certain class.
public int getIdFromClassName(String className){
String query = "SELECT rowid FROM " + CLASSES_TABLE_NAME + " WHERE " + CLASSES_COLUMN_NAME + " = '" + className + "'";
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery(query, null);
return res.getColumnIndex("id");
}
However, this always returns a value of -1.
Any thoughts on what to change to return the proper rowid value?
EDIT:
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(
"create table " + CLASSES_TABLE_NAME + " " +
"(id integer primary key, " + CLASSES_COLUMN_NAME + " text)"
);
db.execSQL(
"create table " + ASSIGNMENTS_TABLE_NAME + " " +
"(id integer primary key, " + ASSIGNMENTS_COLUMN_NAME + " text, " + ASSIGNMENTS_COLUMN_TOTAL_POINTS
+ " INTEGER, " + ASSIGNMENTS_COLUMN_CLASS_ID + " INTEGER)");
}
Try this query below to create a new column name rowID:
Cursor cursor= db.rawQuery("SELECT *,"+CLASSES_TABLE_NAME +".rowid AS rowID"+" FROM "+CLASSES_TABLE_NAME , null);
And after this query you can fetch the real rowid from the rowID column :
while (cursor.moveToNext()) {
long chatRow=cursor.getLong(
cursor.getColumnIndexOrThrow("rowID"));
}
The column returned by your query is called rowid, so you will not find a column called id.
Ensure that you use the same column name in the query and in the call to getColumnIndex.
And the index of this column is always zero; you also need to read the actual value from the column:
int colIndex = res.getColumnIndexOrThrow("rowid"); // = 0
if (res.moveToFirst()) {
return res.getInt(colIndex);
} else {
// not found
}
However, Android has an helper function that makes it much easier to read a single value:
public int getIdFromClassName(String className){
String query = "SELECT rowid" +
" FROM " + CLASSES_TABLE_NAME +
" WHERE " + CLASSES_COLUMN_NAME + " = ?;";
SQLiteDatabase db = this.getReadableDatabase();
return DatabaseUtils.longForQuery(db, query, new String[]{ className });
}
res.getColumnIndex("id") is going to get you the column index of the column with the name "id". and since you are getting -1, it cant find it.. are you sure your id column is not "_id"?
To get this to work you should do something like this..
res.getLong(res.getColumnIndex("_id"));
Cursor.getColumnIndex()
Cursor.getLong()
(I would recommend you use getLong() rather than getInt() because SQLite database ID's can get larger than int's).
You can try this:
public int getIdFromClassName(String className){
String query = "SELECT id FROM " + CLASSES_TABLE_NAME + " WHERE " + CLASSES_COLUMN_NAME + " = '" + className + "'";
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery(query, null);
int id=-1;
If(res!=null&&res.moveToFirst())
id=res.getInt(res.getColumnIndex("id"));
return id;
}
public int getIdFromClassName(String className) {
String query = "SELECT rowid FROM " + CLASSES_TABLE_NAME + " WHERE "
+ CLASSES_COLUMN_NAME + " = '" + className + "'";
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery(query, null);
if (res != null) {
if (res.moveToFirst()) {
do {
return Integer.parseInt(res.getString(res.getColumnIndex("id"))); // if your column name is rowid then replace id with rowid
} while (res.moveToNext());
}
} else {
Toast.makeText(context, "cursor is null", Toast.LENGTH_LONG).show();
}
}
Check your Cursor if its null check your Log that your table is created successfully and if its not null make sure your table has column id in it.

Android, Multiple Tables, SQLite Database

I have another problem with SQLite database in Android OS.
I'm trying to create database with two tables: departments and students.
Departments table contains: dep_id, dep_name and dep_major.
Students table contains: stud_id, dep_id, firstname, surname, email, phone.
How can I put data into this two tables?
There is a Databasehandler.java:
public class DatabaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 2;
private static final String TAG = "DatabaseHandler";
private static final String DATABASE_NAME = "studentsManager2.db";
// pola tabeli "wydzial"
private static final String TABLE_DEPARTMENTS = "departments",
KEY_DEP_ID = "id",
KEY_DEPARTMENT = "wydzial",
KEY_SPECIALIZATION = "kierunek";
// pola tabeli "students"
private static final String TABLE_STUDENTS = "students",
KEY_STUD_ID = "id",
KEY_ID = KEY_DEP_ID,
KEY_FIRSTNAME = "imie",
KEY_SURNAME = "nazwisko",
KEY_INDEKS = "indeks",
KEY_EMAIL = "email",
KEY_NUMER = "numer";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_DEPARTMENTS + "(" + KEY_DEP_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_DEPARTMENT + " TEXT NOT NULL," + KEY_SPECIALIZATION + " TEXT NOT NULL)");
db.execSQL("CREATE TABLE " + TABLE_STUDENTS + "(" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_FIRSTNAME + " TEXT NOT NULL," + KEY_SURNAME + " TEXT NOT NULL," + KEY_INDEKS + " INTEGER," + KEY_EMAIL + " TEXT NOT NULL," + KEY_NUMER + " TEXT NOT NULL)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data.");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_DEPARTMENTS);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_STUDENTS);
onCreate(db);
}
}
Below methods will insert the records in the sqlite database using Datbase helper class:
public void insertDataInBothTables() {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues valuesForDepartmentTable = new ContentValues();
valuesForDepartmentTable.put(KEY_DEPARTMENT , "name");
valuesForDepartmentTable.put(KEY_SPECIALIZATION , "special");
// insert row
long idOfDepart = db.insert(TABLE_DEPARTMENTS, null, valuesForDepartmentTable);
ContentValues values = new ContentValues();
values.put(KEY_FIRSTNAME, "first-name");
values.put(KEY_SURNAME, "sur-name");
values.put(KEY_INDEKS , "inserting-data");
values.put(KEY_EMAIL , "inserting-data");
values.put(KEY_NUMER , "inserting-data");
//Parameter to add department id
values.put(KEY_WYDZIAL, idOfDepart + "");
// insert row
db.insert(TABLE_STUDENTS, null, values);
}

How to insert foreign key in Android?

I have to create 2 to 3 tables and I want to create foreign key of two tables and add into 3rd table. When I run the app data is inserted successfully but foreign key is not showing in the database table structure and table.
Here is my Database class:
public static final String Tsk_id = "task_id";
public static final String Task_Project_NAme = "project_name";
public static final String Task_Team_Member_Name = "assign_to";
public static final String Task_Title = "task_time";
public static final String Task_Start_Date = "start_date";
public static final String Task_CompletionDate = "completion_date";
public static final String Task_CompletionTime = "completion_time";
public static final String Task_Description = "task_description";
public static final String Task_Status = "task_status";
public static final String Task_Is_Active = "IsActive";
public static final String Task_Project_id="project_id";
public static final String Task_Team_Memmber_Id="team_member_id";
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
String CREATE_TASK_TABLE = "CREATE TABLE " + ASSIGN_TASK_TABLE + "("
+ Tsk_id +" integer primary key autoincrement, "
+ Task_Project_NAme + " TEXT,"
+ Task_Team_Member_Name + " TEXT,"
+ Task_Title + " TEXT,"
+ Task_Start_Date + " TEXT,"
+ Task_CompletionDate + " TEXT,"
+ Task_CompletionTime + " TEXT,"
+ Task_Description + " TEXT,"
+ Task_Status + " TEXT,"
+ Task_Is_Active + " TEXT"
+ " FOREIGN KEY ("+Task_Project_id+") REFERENCES " +CONTACTS_TABLE_NAME+" ("+Project_id+")"
+ " FOREIGN KEY ("+Task_Team_Memmber_Id+") REFERENCES " +DEFINE_TEAM_MEMBER_TABLE+" ("+Team_Member_id+")";
db.execSQL(CREATE_TASK_TABLE);
}
public boolean insertTaskDetails(String strTask_Project_NAme,String strTask_Team_Member_Name,
String strTask_Title,String strTask_Start_Date,String strTask_CompletionDat,
String strTask_CompletionTime,String strTask_Description,
String strTask_Status,String strTask_Is_Active)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(Task_Project_NAme, strTask_Project_NAme);
contentValues.put(Task_Team_Member_Name, strTask_Team_Member_Name);
contentValues.put(Task_Title, strTask_Title);
contentValues.put(Task_Start_Date, strTask_Start_Date);
contentValues.put(Task_CompletionDate,strTask_CompletionDat);
contentValues.put(Task_CompletionTime,strTask_CompletionTime);
contentValues.put(Task_Description, strTask_Description);
contentValues.put(Task_Status, strTask_Status);
contentValues.put(Task_Is_Active,strTask_Is_Active);
db.insert(ASSIGN_TASK_TABLE, null, contentValues);
db.close();
return true;
}
+ " FOREIGN KEY ("+Task_Project_id+") REFERENCES " +CONTACTS_TABLE_NAME+" ("+Project_id+")"
for this line of code where is Task_Project_id column in the while creating the table.. please check.
You need to create a particular column to reference as foreign key.
same with this line too
" FOREIGN KEY ("+Task_Team_Memmber_Id+") REFERENCES " +DEFINE_TEAM_MEMBER_TABLE+" ("+Team_Member_id+")";

Categories