what is missing in my sqlite syntax for foreign key? - android

I created two sqlite tables on android
phone table with primary key "id"
CREATE TABLE BLOCKED_PHONES_TABLE ( id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL DEFAULT 1, KEY_PHONE TEXT UNIQUE,KEY_IS_BLOCKED BIT )
comment table with foreign key "id"
CREATE TABLE COMMENTS_TABLE ( id INTEGER, KEY_COMMENT_TEXT TEXT, FOREIGN KEY(id) REFERENCES BLOCKED_PHONES_TABLE(id))
why does the comment table don't refer id as a foreign key?
otherwise it won't have ids that are missing in the phone table.
how can I know my sqlite version?

For backwards compatibility, foreign key checking is disabled by default.
You need to call setForeignKeyConstraintsEnabled in onConfigure.

Related

Foreign Key Android DATABASE

I'm confused about the correct usage and implementation of the "Foreign KEY" in the SQLite Database in Android.
I created a DB with several relations, as following:
CREATE TABLE "food" (
`_id` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
`name` TEXT NOT NULL,
`description` TEXT,
`category_id` INTEGER,
FOREIGN KEY(`category_id`) REFERENCES food(_id) )
CREATE TABLE `category` (
`_id` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
`cagory_name` TEXT NOT NULL)
CREATE TABLE "favourites" (
`_id` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
`id_favourite` INTEGER NOT NULL,
FOREIGN KEY(`id_favourite`) REFERENCES food ( _id ))
As you can see, there are 3 tables and the _id of "food" is the foreign key connecting the table "category" and "favourites".
Now, in Android I don't see happening ANYTHING that proves that I created such a relation among tables. Do I miss some declaration to make it effective?
How does it work in Android?
The category_id foreign key reference seems odd.
Is there a reason it's:
FOREIGN KEY(`category_id`) REFERENCES food(_id)
and not
FOREIGN KEY(`category_id`) REFERENCES category(_id)
To make sure foreign key constraints are enforced, in SQLite run
PRAGMA foreign_keys = ON;
See http://www.sqlite.org/foreignkeys.html for documentation.

SQLite PRIMARY key AutoIncrement doesn't work

I'm trying to a have a table with an auto incremented primary key. The SQL query for table creation is included.
Problem is the auto-increment does not work. Meaning when I insert a row with NULL as the value of conversation_id it just inserts null. I have this problem on multiple tables.
-- Table: conversations
CREATE TABLE conversations (
conversation_id INTEGER (64) PRIMARY KEY
UNIQUE,
target_id BIGINT (64),
sender_id BIGINT (64),
status STRING (16) NOT NULL
DEFAULT unseen,
is_group INTEGER (1) NOT NULL
DEFAULT (0),
last_update INTEGER (32) DEFAULT (0),
target_name STRING (64),
target_photo STRING (256),
unread_count INTEGER (10) DEFAULT (0),
last_message STRING (256)
);
The following is the method I use to insert into table:
public Conversation addConversation(Conversation conversation) {
SQLiteDatabase db = getWritableDatabase();
ContentValues row = new ContentValues();
row.put("target_id", conversation.getTargetID());
row.put("sender_id", conversation.getSenderID());
row.put("target_name", conversation.getTargetName());
row.put("target_photo", conversation.getTargetPhoto());
row.put("status", conversation.getStatus());
row.put("unread_count", conversation.getUnreadCount());
row.put("last_message", conversation.getLastMessage());
conversation.setConversationID(db.insert(TBL_CONVERSATIONS, null, row));
Log.d(TAG, "conversation added: "+conversation.getConversationID());
db.close();
return conversation;
}
The curious thing here is when I retrieve the insert id from insert method it returns the correct value, but the actual database field is null.
If I understand correctly A column declared INTEGER PRIMARY KEY will autoincrement. [Cite]
From documentation:
A table created using CREATE TABLE AS has no PRIMARY KEY and no
constraints of any kind. The default value of each column is NULL.
You don't have to add UNIQUE constraint on a COLUMN that has PRIMARY KEY constraint.
Explanation:
A UNIQUE constraint is similar to a PRIMARY KEY constraint, except
that a single table may have any number of UNIQUE constraints.
Instead add NOT NULL.
This is why:
According to the SQL standard, PRIMARY KEY should always imply NOT
NULL. Unfortunately, due to a bug in some early versions, this is not
the case in SQLite. Unless the column is an INTEGER PRIMARY KEY or the
table is a WITHOUT ROWID table or the column is declared NOT NULL,
SQLite allows NULL values in a PRIMARY KEY column. SQLite could be
fixed to conform to the standard, but doing so might break legacy
applications. Hence, it has been decided to merely document the fact
that SQLite allowing NULLs in most PRIMARY KEY columns.
I recommend using this Column definition:
CREATE TABLE conversations (
conversation_id INTEGER PRIMARY KEY NOT NULL AUTOINCREMENT,
...
}
Most likely the return value you are seeing is the row's ROWID. A ROWID is a hidden column available in every table, unless explicitly removed. According to the official documentation, when you define an INTEGER PRIMARY KEY, it should automatically become an alias for the ROWID. That's also why AUTOINCREMENT is not needed when you define your column in this way.
With one exception noted below, if a rowid table has a primary key
that consists of a single column and the declared type of that column
is "INTEGER" in any mixture of upper and lower case, then the column
becomes an alias for the rowid. Such a column is usually referred to
as an "integer primary key". A PRIMARY KEY column only becomes an
integer primary key if the declared type name is exactly "INTEGER".
Other integer type names like "INT" or "BIGINT" or "SHORT INTEGER" or
"UNSIGNED INTEGER" causes the primary key column to behave as an
ordinary table column with integer affinity and a unique index, not as
an alias for the rowid.
See: CREATE TABLE documentation
Either your column is not an INTEGER, or it is not a PRIMARY KEY. Taking a closer look at your create-statement I can see one or two possible culprits.
UNIQUE vs. PRIMARY KEY
A primary key is unique by default. According to the syntax definition (which you can find on the same documentation page as the citation above) you should choose either PRIMARY KEY or UNIQUE, not both.
COLUMN length restrictions
ROWID is already 64-bit by default. You have specified length 64, but lengths are not specified in bits. You may have specified a 64-byte integer here, which I'm sure was not intended. This should actually not be a problem however, since SQLite ignores length-constraints. So it is not meaningful to specify them.
TLDR
Replace this code:
conversation_id INTEGER (64) PRIMARY KEY UNIQUE
With this:
conversation_id INTEGER PRIMARY KEY AUTOINCREMENT
I just put autoincrement in the query and it works fine .
like this
id integer primary key autoincrement

Using different IDs for multiple table in SQLITE

I am using SQLite to work on an android application. What I have learned so far is that a table made in SQLite requires a column called _id. So, for instance, to create a table, I use the following SQL Statement:
CREATE TABLE IF NOT EXISTS Semesters(
_id INTEGER PRIMARY KEY AUTOINCREMENT,
semester_name TEXT,
is_current TEXT
GPA REAL);
However, now if I want to create a seperate table in the same database, what would I name the primary key column? For instance, this is the table I want to create:
CREATE TABLE IF NOT EXISTS Classes(
_id INTEGER PRIMARY KEY AUTOINCREMENT,
course_name TEXT);
Now, both the semesters table and the courses table have a column called _id, and if I want to make a foreign key reference to the _id column in the semesters table, I will have to call it by the table name. Is there any way to make this simpler by using different names for ids?
Thanks.
For example, you make a third table and want to use both primary keys from your tables as foreign keys:
CREATE TABLE ClassSemester(
_id INTEGER PRIMARY KEY AUTOINCREMENT,
semester_id INTEGER,
class_id INTEGER,
FOREIGN KEY(semester_id) REFERENCES Semesters(_id),
FOREIGN KEY(class_id) REFERENCES Classes(_id)
);
More details in here:
http://www.sqlite.org/foreignkeys.html

Multi Primary Keys in Android SQLite

In SQLite for Android what is the correct way to add multi primary keys?
Currently I have:
String Create_table = "CREATE TABLE project ( keyId INTEGER PRIMARY KEY, keyName TEXT PRIMARY KEY)";
The alternative method I thought of was:
String Create_table = "CREATE TABLE project (keyID INTEGER, keyName TEXT, PRIMARY KEY(keyID, keyName))";
Are both valid? If so, which is better? Also how do I disallow NULL values?
No it's not possible to create multiple primary keys for a single table. It's basic rule of any SQL. However you can use other constraint like UNIQUE with index to achieve this.
This won't be valid SQL Syntax:
String Create_table = "CREATE TABLE project ( keyId INTEGER PRIMARY KEY, keyName TEXT PRIMARY KEY)";
In other way you can create primary key for multiple column as follows:
Create Table yourTableName (col1, col2, col3, PRIMARY KEY (col1, col2));
How do I disallow NULL values?
you can use NOT NULL Constraint , it will not allow you to enter NULL values.
You may use one primary key , more foreign keys in one table

Android: mySQL, create table command

I'm trying to create a table and I've tried so many times to figure this out... for some reason it won't accept this.. it's saying something about the auto_increment
create table if not exists Assignments(
id auto_increment primary key,
class_name VARCHAR(30),
assignment_name VARCHAR(30) not null,
due_date VARCHAR(30) not null,
notes VARCHAR(30));
whats the problem?
EDIT: i am trying to use SQLite eventually but this command was written on my mySQL thru WAMP
First of all, Android uses SQLite, so your mysql tag is slightly incorrect unless I'm missing something you're doing.
Secondly, you would say
CREATE TABLE ASSIGNMENTS(id INTEGER PRIMARY KEY, class_name TEXT, assignment_name TEXT NOT NULL, due_date TEXT NOT NULL, notes TEXT);
"autoincrement" is handled automatically if you set your primary key as an INTEGER type, even though under the covers SQLite uses strings for everything
reference: SQLite datatypes
further reference: INTEGER PRIMARY KEY
Even more reference: "If an INSERT statement attempts to insert a NULL value into a rowid or integer primary key column, the system chooses an integer value to use as the rowid automatically. A detailed description of how this is done is provided separately."
It is autoincrement, not auto_increment

Categories

Resources