friends,
I am doing an Android project in my company, still some small work is remaining, I need your help to complete the task.
The problem is...
I have created two tables in which, table1 has an empty column, for purpose for saving name...
The table2 has a list of names, the objective is only the names from this list should be should be saved in the table1's empty column other than that it shouldn't accept any of the name typed manually.
You appear to want to make the list of names a validation: if the user wishes to save a name to table1, the name must already exist in table2.
Typically this would be done as in the following example, in which only the products listed in PRIZEPRODUCTS can be entered into PRIZEWINNERS table: someone could not win a Boat, for example, given the data below:
PRIZEPRODUCTS
id
productname
1|TV
2|iPad
3|backpack
PRIZEWINNERS
id
productid
winner
ALTER TABLE PRIZEWINNERS
ADD CONSTRAINT PRIZEWINNERS_PRIZEPRODUCTS_FK
FOREIGN KEY(productid) REFERENCES PRIZEPRODUCTS(id)
SQLite doesn't create the foreign key using ALTER TABLE but as part of the create-table statement. See here for the syntax. For enabling foreign key support in Android (2.2), see here.
Now, you can establish the foreign key on the [productname] column if [productname] were the key of PRIZEPRODUCTS. In other words, you could make person-name the key of the table rather than having a PersonID. But if that name is changed in the validation table, it can break the foreign key relationship, unless ON UPDATE CASCADE is enabled, but I am not sure if this is supported in Android.
I hope below query will work for you.
insert into table1(name) values (select name from table2 where id=?).
Thanks.
Related
For an android room interface, I want to get the autogenerated id (as primary key of a record just inserted), so that I can put it in the object without executing a select after insert, where the select might return the wrong record if there is no other unique attribute, or set of attributes for those record types.
For example, for 2 people having the same name being inserted into the same table. You might say generate a composite key to make a unique set. However that might involve the addition of new fields that are otherwise not required.
I've seen various links, including those below. Some mention that it is the row id that is returned if the insert method is declared to return integer (or long), and succeeds.
However it is my understanding that the row id cannot be assumed to be the same as the primary key. (Refer Rowid after Insert in Room).
I cannot comment on any posts because I don't have enough reputation points.
I appreciate any comments regarding what might be a good/typical approach to this problem.
These are the posts I have looked upon:
Android Room - Get the id of new inserted row with auto-generate
https://developer.android.com/training/data-storage/room/accessing-data
https://commonsware.com/AndroidArch/previews/the-dao-of-entities
Late answer just for anyone seeing this question in the future
from SQLite docs it says :
The PRIMARY KEY of a rowid table (if there is one) is usually not the
true primary key for the table, in the sense that it is not the unique
key used by the underlying B-tree storage engine. The exception to
this rule is when the rowid table declares an INTEGER PRIMARY KEY. In
the exception, the INTEGER PRIMARY KEY becomes an alias for the rowid.
therefore it's correct to assume that the rowId returned by insert query is the same as the autoincremented-primary-key
Say I have table Book and table Page. Say that table Page has book's dbId as a foreign key. When I do an INSERT OR REPLACE on a Book row, does that change the dbId of the book?
Say the book is title="Song of Songs", author="King Solomon",pages=50" say that I want to change the title of the book and that will lead to replacement of the row. So the question is: will the replace cause the dbId of the book to change? I imagine it shouldn't, but I just don't know.
So this is about ON CONFLICT REPLACE
The documentation says about INSERT OR REPLACE:
When a UNIQUE or PRIMARY KEY constraint violation occurs, the REPLACE algorithm deletes pre-existing rows that are causing the constraint violation prior to inserting the current row and the command continues executing normally.
If the new dbId has the same value as the old one, it does not change (obviously). But if the constraint violation happens in another column, the new dbId might have a different value (especially if it's an autoincrementing column).
For implementing your idea :
1:) First get to foreign key from the first table using select query.
2:) then create a function with a parameter through which you can pass this foreign key in process of getting relevant data using the foreign key from the foreign table.
3:) Now use below query for fetching to related data using that key-
databaseObject.update(TABLE_NAME, values, COLOMN_NAME + " = ?",
Array_of_replacing_values);
I am new in programming, and I want to ask question regarding database schema (I'm using SQLite Database for Android Development)
I have some table, let say :
MsMember
MemberId
Password
MsGroup
GroupId
GroupName
MsAnnouncement
AnnouncementId
AnnouncementName
MsComment
CommentId
CommentContent
MsTodolist
TodolistId
TodolistTitle
And I want everytime a new row has been inserted to (at least one of) all five tables above, it will create a notification to user, as far as I know, with this concept, I should create a table to store every detail of notification then shows it to user..
And my best opinion so far is I create a table let say MsNotification, then to connect all five tables with this MsNotification I should have foreign key referring to each table..
My Question is would it be possible (and effective) to have a column that has more than one references?
Example :
Foreign key (SourceId) Referring MsMember (MemberId),
Foreign key(SourceId) referring MsComment (CommentId),
Foreign key (SourceId) referring MsAnnouncement (AnnouncementId), and so on.
or is there any better way to implement this concept?
Thank you in advance
No ,you can not assign single foreign key to multiple column .
But you can put multiple foreign key in single table
I am having a table with 'int' column. During software upgrade, I want to change it to 'long' data type. It seems SQLite does not provide an option (in alter statement) to change/modify column properties. Since I want to do an upgrade, the table might contain data which the user should not lose. So please suggest me a good method to change the column data type property without data loss.
One way suggested in the search links is to create a temporary table, copy the records from the existing table, delete the existing table, and rename the temporary table. I doubt that is efficient.
Your help appreciated!
Regards
Vivek Ragunathan
I used the follow statements to change the type of the column.
CREATE TABLE IF NOT EXISTS **TEMP_TABLE** (id integer primary key autoincrement, **col2change integer not null**, ...)
INSERT INTO TEMP_TABLE SELECT * FROM EXISTING_TABLE
DROP TABLE EXISTING_TABLE
ALTER TABLE TEMP_TABLE RENAME TO EXISTING_TABLE
I changed the int type column in the existing table to integer type. For a few hundred rows, it was reasonably fast.
SQLite3 columns do not have data types, only affinities -- there is no benefit in changing the column type from int to long.
If a wrapper program is truncating values before giving them to SQLite3, there is a way to fix this by editing the schema. It is a dangerous operation, so do it only after backing up your database. The schema is stored in the table sqlite_master; normally it is read-only, but you can modify it if you enable it with the writable_schema pragma. Be careful to only make changes that do not invalidate your data; you may change int to long int since they both have INTEGER affinity.
From SQLite documentation
It is not possible to rename a column, remove a column, or add or
remove constraints from a table.
Check this link
Please do remember that column data types are not rigid in SQLite. Check this link
Edit:
Following your comments on another answer, I guess the option you mentioned - working through the temp table - is the only one, which is not efficient off course.
you could add a new colum, copy the values form the old to the new column, delete the old column and then rename the new column to the old name
AFAIK there is no way in Android to change column data types once a table is created and used. The practiced way is to make a new table and copy the data which you read about
i am getting information from user in sqlite database.
But when i insert same record which is already in database it is added again.
how i can stop duplication of record in sqlite. I am developing this in android.
I am using mobile number as primary key. still it add that record in database.
Please suggest me appropriate solutions.
Thanks in advanced.
Be aware of the limitations of REPLACE or INSERT OR REPLACE as these will overwrite any custom data your app user has added to these rows in the database - it is not as advanced as UPSERT in other SQL databases.
As mentioned in a previous post you really need to identify what the primary key could be and use this information to either update old data or to remove an old row before inserting the fresh one.
If this is not possible then you could always DELETE FROM my_table or DROP my_table before running the insertions so that there will be no duplicates. This will (for better or worse) also make sure that data that is missing from new imports is not left lying around in your app.
make sure you have set your phone number as Primary Key at the time you created the table.
for example:
String query = "CREATE TABLE IF NOT EXISTS PhoneBook ("+
"TelNum VARCHAR(100) PRIMARY KEY NOT NULL,"+
"Address TEXT);";
db.execSQL(query);
and in case you want to enforce foreign keys defined in your table then call the following method before doing anything in your database
db.execSQL("PRAGMA foreign_keys = ON;"); //enforcing FK
Use REPLACE INTO keyword:
REPLACE INTO my_table (pk_id, col1) VALUES (5, '123');
This automatically identifies the primary key and finds a matching row to update, inserting a new one if none is found.