In my android project's SqLite database I have to create a foreign key which is the primery key of the table. I wrote the sql statement as below using SQLiteManager.
CREATE TABLE OBTTourVehicleUpdate
(
TourHeaderCode INT PRIMARY KEY NOT NULL,
TourVehicleProcessCode INT NOT NULL,
VehicleCode CHAR(10),
TourStart TEXT ,
TourEnd TEXT ,
LastMilage DOUBLE,
NewMilage DOUBLE,
CONSTRAINT FOREIGN KEY (TourHeaderCode) REFERENCES OBTTourHeader(TourHeaderCode)
);
It gives me an error message saying that
Internal Error. near FOREIGN: syntax error.
The table structure of two tables are as below.
how can I fix this.
Remove CONSTRAINT from your code. Just do the
FOREIGN KEY (TourHeaderCode) REFERENCES OBTTourHeader(TourHeaderCode).
Remember to call the table on the onCreate() and onUpdate() and also update the DB_version. And to be on the safe side, do not declare your FK as the PK too.
You get that error because your syntax is indeed incorrect.
Read the official SQLite documentation to learn more about how it should be used.
CREATE TABLE OBTTourVehicleUpdate
(
TourHeaderCode INT PRIMARY KEY NOT NULL,
TourVehicleProcessCode INT NOT NULL,
VehicleCode CHAR(10),
TourStart TEXT ,
TourEnd TEXT ,
LastMilage DOUBLE,
NewMilage DOUBLE,
FOREIGN KEY(TourHeaderCode) REFERENCES OBTTourHeader(TourHeaderCode)
);
Something like that should work.
CREATE TABLE OBTTourVehicleUpdate
(
TourHeaderCode INT PRIMARY KEY NOT NULL,
TourVehicleProcessCode INT NOT NULL,
VehicleCode CHAR(10),
TourStart TEXT ,
TourEnd TEXT ,
LastMilage DOUBLE,
NewMilage DOUBLE,
FOREIGN KEY(TourHeaderCode) REFERENCES OBTTourHeader(TourHeaderCode)
);
You don't need to use CONSTRAINT in your query. Follow this article about Foreign Key Constraints
Related
I am writing an Android app and need a database for it. I will have three tables but only managed to make one right now. I do them in the console to debug and to implement them in my Javacode later. The following statements were succesfull:
sqlite3 progressapp.db
CREATE TABLE Z_Type(_Z_T_ID INTEGER PRIMARY KEY NOT NULL,
Description TEXT NOT NULL, Unit TEXT NOT NULL);
But now I want to refference the PK of T_Type in my other table:
CREATE TABLE goals (_Z_id INTEGER PRIMARY KEY NOT NULL, Title TEXT NOT NULL,
Type INTEGER NOT NULL, FOREIGN KEY(Type) REFERENCES Z_Type(_Z_T_ID),
Timeframe TEXT, Goaldate INTEGER);
Is Type INTEGER NOT NULL, FOREIGN KEY(Type) REFERENCES Z_Type(_Z_T_ID) a valid SQLite Statement in Android? It says "Error: near "Timeframe": syntax error" But I simply can't find it due to lack with SQL Experience I guess.
Is there a better way to reference the FK maybe?
Try this:
CREATE TABLE goals (_Z_id INTEGER PRIMARY KEY NOT NULL, Title TEXT NOT NULL,
Type INTEGER NOT NULL,Timeframe TEXT, Goaldate INTEGER, FOREIGN KEY(Type) REFERENCES Z_Type(_Z_T_ID));
I think that the order is important.
For further documentation you could visit sqlite.org/foreignkeys.html
You can define the reference as part of the column definition
CREATE TABLE goals (_Z_id INTEGER PRIMARY KEY NOT NULL, Title TEXT NOT NULL,
Type INTEGER NOT NULL REFERENCES Z_Type(_Z_T_ID),
Timeframe TEXT, Goaldate INTEGER);
In a sqlite CREATE TABLE statement, column definitions come first and table constraints only after that.
FOREIGN KEY(Type) REFERENCES Z_Type(_Z_T_ID) is a table constraint that should go at the end.
This is my SQLite table structure
CREATE TABLE tbl_district (
districtId INTEGER PRIMARY KEY not null,
districtName TEXT unique NOT NULL
);
CREATE TABLE tbl_route (
routeId INTEGER,
districtId INTEGER NOT NULL REFERENCES tbl_district (districtId) ON DELETE CASCADE ON UPDATE CASCADE,
routeName TEXT NOT NULL,
primary key (routeId , districtId)
);
CREATE TABLE tbl_city (
cityId INTEGER PRIMARY KEY,
routeId INTEGER NOT NULL REFERENCES tbl_route (routeId) ON DELETE CASCADE ON UPDATE CASCADE,
cityName TEXT NOT NULL
);
If i execute
insert into tbl_district ( districtId, districtName) values (1,'Sri Lanka')
It works as it should
But if i execute
replace into tbl_district ( districtId, districtName) values (1,'Sri Lanka')
It gives following error
Error while executing query: foreign key mismatch - "tbl_city" referencing "tbl_route"
Any idea to resolve this?
Thanks in advance!
The documentation says that
the parent key columns must be collectively subject to a UNIQUE constraint or have a UNIQUE index.
The routeId column is the parent key of the foreign key in tbl_city, but has no UNIQUE constraint.
(Your REPLACE statement is not directly related to this; it's just when the database happend to notice the error.)
im creating a Table with this command :
create table if not exists Event ( _id long INTEGER AUTO INCREMENT,repeatEvery long ,repeating int ,startTime long ,title text ,primary key (_id) );
also tried id without the _ prefix, and then i fetch all rows with
database.query("Event",null , null, null, null, null, null);
and then i go over the results printing the ID column :
if (c.moveToFirst()) {
do {
System.out.println(c.getLong(c.getColumnIndexOrThrow("_id")));
} while (c.moveToNext());
}
all of the results are zeros! idea any one?
SQLITE by default adds an INTEGER AUTOINCREMENT for you. Search for ROWID. The creation of a column that replicates this functionality will just be created as an alias to ROWID.
I did some more digging around and found out what some of the issues are. First of all, SQLITE is garbage.
Here is the correct SQL statement you need to use.
CREATE TABLE Event (_id INTEGER PRIMARY KEY AUTOINCREMENT,repeatEvery long ,repeating int ,startTime long ,title text)
I issued the one in your code sample, and it had the type of the _id column as "INTEGER AUTO INCREMENT". The SQLITE parser is very generous and accepted that as a datatype. It had no idea what to do with it, and just treated it as a blob, and none of the constraints worked. So, even though your DDL was incorrect, SQLITE was nice enough to take it's best guess at what was wrong and didn't bother to let you know. :[
If you print the schema of your apps' Event table, you'll should see the INTEGER AUTO INCREMENT issue.
Another issue to watch out for,
If you're writing your insert statements on your own, you need to write in one of these two ways.
insert into Event (repeatEvery, repeating, startTime, title) values (1,2,3, "title");
or
insert into Event values (NULL, 1,2,3, "title");
the SQLITE Helper class should handle this for you.
From the sqlite docs it looks like the definition should be changed a little.
the definition should probably be:
create table if not exists Event ( _id INTEGER PRIMARY KEY, repeatEvery long, repeating int, startTime long, title text );
Simply :
create table if not exists Event ( _id INTEGER PRIMARY KEY,repeatEvery long ,repeating int ,startTime long ,title text );
for some reason, should not declare column type...
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
I have a table with a composite primary key and I am having trouble inserting. The code used to create the table is:
CREATE TABLE ClassEvent (
EventName varchar(10) NOT NULL,
CourseId varchar(10) NOT NULL,
EventType varchar(20),
EventWeight number(3),
DueDate DATE NOT NULL,
FOREIGN KEY (CourseId) REFERENCES Courses(CourseId),
PRIMARY KEY (CourseId, EventName));
The problem I am having is when I want to insert records that have values that may not be unique for the columns CourseId or EventName, but are a unique combination of the 2.
for example, if I try to run the following 2 inserts:
INSERT INTO ClassEvent VALUES('Assignment 1','60-415','Assignment',10,'12/10/2010');
INSERT INTO ClassEvent VALUES('Project 1','60-415','Project',15,'5/12/2010');
I get the following error:
Error: columns CourseId, EventName are not unique.
and the second insert does not make it into the DB. Why does this error out? I thought that a composite primary key requires that the combination of both values are unique. In my above inserts, the values for the EventName column are different even though the values for CourseId are the same. Shouldn't this be seen as 2 unique combinations and thus 2 different primary keys?
My table needs to be able to hold several different events for each CourseId, but each Event must be unique for each Course. I need to be able to insert values into the table like:
EventName CourseId
Assignment 1 60-415
Project 1 60-415
Assignment2 60-415
Project 2 60-415
Assignment 1 60-367
Project 1 60-367
and so on. Can anyone tell me how I can get this to work? Why are these composite PK's not being seen as unique entries? Any help would be much appreciated.
Here is the java function I am using for the insert:
public void addNewClassEvent(ContentValues values) {
SQLiteDatabase db = openConnection();
db.insert("ClassEvent", null, values);
db.close();
}
Could this be causing the problem?
You can have a composite primary key in SQLite, but you
have to create the key when you create the table:
CREATE TABLE example1(
field1 FLOAT,
field2 TEXT,
PRIMARY KEY(field1, field2)
);
You cannot create the primary key after the fact using ALTER TABLE.
On the other hand, you can create a UNIQUE INDEX after the fact
which has essentially the same effect as a PRIMARY KEY:
CREATE UNIQUE INDEX pk_index ON "table1"("field1","field2");
I am not sure how you have created, the tables, and if you have added the primary index later, but grab the database to your desktop, and check out how works in a desktop environment.
You can't make combinations like that, but you don't need them. What is stopping you from just having a truly id column ?