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+"));";
Related
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);
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.
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);
}
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+")";
This is my DBInfo class:
public class DBInfo stars table
static final String STARS = "stars";
static final String FIRST_NAME = "first_name";
static final String LAST_NAME = "last_name";
static final String CREATE_STAR_TABLE = "CREATE TABLE " + STARS +
"(" + _ID + " integer primary key autoincrement, "
+ FIRST_NAME + " text not null, "
+ LAST_NAME + " text not null);";
//stars in movies
static final String STARS_IN_MOVIES = "stars_in_movies";
static final String STAR_ID = "star_id";
static final String MOVIE_ID = "movie_id";
static final String CREATE_STAR_IN_MOVIE_TABLE = "CREATE TABLE " + STARS_IN_MOVIES +
"(" + STAR_ID + " integer not null, "
+ MOVIE_ID + " integer not null, "
+ "FOREIGN KEY (" + MOVIE_ID + ") REFERENCES "+ MOVIES +" (" + _ID + ") "
+ "FOREIGN KEY (" + STAR_ID + ") REFERENCES "+ STARS +" (" + _ID + "));";
//statistics table
static final String STATISTICS = "statistics";
static final String RIGHT = "right";
static final String WRONG = "wrong";
static final String CREATE_STATISTICS_TABLE = "CREATE TABLE " + STATISTICS +
"(" + _ID + " integer primary key autoincrement, "
+ RIGHT + " int not null default 0, "
+ WRONG + " int not null default 0);";
}
And now I want to implement this class toy DBAdapter class which already extends SQLiteOpenHelper
public class DbAdapter extends SQLiteOpenHelper implements DBInfo{
private static final String DATABASE_NAME = "quizdb";
private static final int DATABASE_VERSION = 9;
private static final String MOVIES_FILE = "movies.csv";
private static final String STARS_FILE = "stars.csv";
private static final String STARS_IN_MOVIES_FILE = "stars_in_movies.csv";
private static SQLiteDatabase mDb;
private static Context mContext;
public static SQLiteDatabase getSQLiteDatabase(Context ctx){
if(mDb == null){
new DbAdapter(ctx);
}
return mDb;
}
And I am getting the following error:
The type DBInfo cannot be a superinterface of DbAdapter; a superinterface must be an interface
You cannot implement class.
Make DBInfo an interface
implements DBInfo
This won't work since you can implement only interface and your DBInfo is class. So you have only choice:
Change your DBInfo class to interface
In your case only way is to change it to interface1 or change whole application logic. By the way it's very good practise to create interface that will hold static constants:
public interface DBInfo {
public static final String STARS = "stars";
public static final String FIRST_NAME = "first_name";
public static final String LAST_NAME = "last_name";
}
1 Because Java doesn't support multi-inheritance as was suggested.
You can only implement interfaces, not classes. This would seem like a situation where you should try composition instead of inheritance (have an instance of DBInfo in DbAdapter instead of inheriting it).