How to Apply Primary Key on the Text Fields in Android Database

Is it possible to apply primary key on the text fields in android database

as per the faq of sqlite documentation, using TEXT as a datatype for primary key should work.

i used your query and here it is, the table is created.

CREATE TABLE contacts ( email text primary key not null, name text not null);

INSERT INTO contacts VALUES ('sample@email.com', 'sample')
INSERT INTO contacts VALUES ('people@email.com', 'sample')

Sample Image

Sample Image

now here is where it went wrong.

when i ran this again

INSERT INTO contacts VALUES ('sample@email.com', 'sample')

nothing happened, no errors.
But it did not update the record. so i conclude data integrity is there but you don't get any feedback about the failure.

how to add primary key to text datatype in android sqlite?

You don't create primary keys like that in SQLite. I have not tested the following, but according to the documentation it should work:

private static final String CREATE_NEWCUSTOMER = "create table newcustomer (_id integer autoincrement, cname text, date text, caddress text, PRIMARY KEY(_id, cname));";

Is it possible using String as PrimaryKey in Android Room

Yes, you can use a String as a @PrimaryKey.

Additionally, I also recommend making use of Kotlin's data class to simplify your entities. For example:

@Entity
data class Crew(@PrimaryKey val uuid: String, val name: String) {
// Put any functions or other members not initialized by the constructor here
}

How to add primary key in room database?

One does not have to run CREATE TABLE SQL, when having tableName and @ColumnInfo annotations present. Add a primary key entry_id (since the class_id barely is unique):

@Entity(
tableName = "performance",
foreignKeys = {
@ForeignKey(
entity = StudentEntry.class,
parentColumns = {CLASS_ID, STUDENT_ID},
childColumns = {CLASS_ID, STUDENT_ID},
onDelete = CASCADE,
onUpdate = CASCADE
)
}
)
public class PerformanceEntry {

/* Fields */
@ColumnInfo(name = "entry_id")
@PrimaryKey(autoGenerate = true)
private int entryId;

...
}

How to make two fields as one primary key in ormlite?

@DatabaseField(columnName = "_id",id = true,generatedId = true)
private long _id;

_id it is primary key when you used generatedId = true;



Related Topics



Leave a reply



Submit