SQLite3 insertion into foreign key table doesn't work - sqlite

I have an SQLite3 database running on a Python Flask server. I am trying to insert values into foreign key database but the values for the foreign key are set at Null.
In my Flask application.py file:
from flask import Flask
from cs50 import SQL
app = Flask(__name__)
db = SQL("sqlite:///test.db")
db.execute("CREATE TABLE 'people' ('id' integer, 'name' varchar(100), PRIMARY KEY(id))")
db.execute("CREATE TABLE 'friendships' (person_id INTEGER,'id' smallint, 'friends' boolean, FOREIGN KEY(person_id) REFERENCES people(id))")
At some point in the code I want to insert a 'friendship' into the referenced database, assuming I have two people with ids 1 and 2 in the 'people' table. Therefore, I run the code:
db.execute("INSERT INTO friendships (person_id, id, friends) VALUES (1, 2, 1)")
This leaves me with a null value for this inserted row in the person_id field, and have no clue why it has happened. I'm also unable to find anything on similar problems online, so I would really appreciate any help.
Edit:
The code works on itself but I tried to insert an input from a non-existent form input value of person_id from the client-side to the server. This resulted in null values being submitted to the server, consequently ending up in the database.

Related

I can't add foriegn key to my existing table. | sqlite3

So i am trying to complete finance. Following is the .schema:
sqlite> .schema
CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, username TEXT NOT NULL, hash TEXT NOT NULL, cash NUMERIC NOT NULL DEFAULT 10000.00);
CREATE TABLE sqlite_sequence(name,seq);
CREATE TABLE history(
symbol TEXT, name TEXT, shares INTEGER, price NUMERIC, time DATETIME
);
CREATE UNIQUE INDEX username ON users (username);
When i try to add foriegn key to history table it always return error. Here is my code:
sqlite> ALTER TABLE history ADD COLUMN id INT;
sqlite> ALTER TABLE history ADD FOREIGN KEY(id) REFRENCES users(id);
Parse error: near "FOREIGN": syntax error
ALTER TABLE history ADD FOREIGN KEY(id) REFRENCES users(id);
^--- error here
I think based on what I see in the sqlite docs that the statement should be together with the ADD column:
ALTER TABLE history ADD COLUMN id INTEGER REFERENCES users(id);
But you please check me on this syntax! Another option is to take care of creating the constraint at the same time that you create the table.
CREATE TABLE history(
symbol TEXT,
name TEXT,
shares INTEGER,
price NUMERIC,
time DATETIME,
id INTEGER,
FOREIGN KEY (id)
REFERENCES users (id));
It might not be something you have realized (yet) but every database has its unique flavor of SQL, so despite there being a SQL standard there are often little differences in the syntax of SQL for specific db implementations. So you always have to beware of this when looking up commands for your sql db.
Further detail on Sqlite foreign key constraints can be found here:
https://www.sqlitetutorial.net/sqlite-foreign-key/

Create table with auto increment

I have to create a table with autoincrement column. I am creating an web app with sqlite as a background and sql alchemy is the orm layer.Python and Flask as front end. I am creating some department list and department id should be auto incremented.When I try to add department through UI I dont provide department id.Because department id is the primary key and should be auto incremented.I have added the department name and department jobs through UI without any error.But when I try to list the departments list I am getting error.
AttributeError: 'NoneType' object has no attribute 'department_id'
What I tried is,My sqlite
create table Departments(department_id primarykey integer autoincrement,department_name char,department_jobs char);
When I try creating this schema I am getting an error called 'syntax error near autoincrement'
I tried by using capital letter,auto_increment,auto increment.
Nothing is working
My sql alchemy looks like this
class Departments(db.Model):
"Adding the department"
department_id = db.Column(db.Integer,primary_key=True)
department_name = db.Column(db.String(50),nullable=False)
department_jobs = db.Column(db.String(40),nullable=False)
What I am expecting here is how do I do the auto incrementin sqllite and sqlalchemy so that I can use it in both frontend and backend.
You have coded PRIMARYKEY instead of PRIMARY KEY and you should also code INTEGER PRIMARY KEY as the column type should appear first.
There is no need, from your explanation, to code AUTOINCREMENT.
Not using AUTOINCREMENT will be more efficient and will as far as you are concerned do the same thing. i.e. if the value for the department_id is not supplied, then SQLite will automatically generate a value which will be 1 for the first row that is inserted and then typically 1 greater for the next row and so on (SQLite does not guarantee montonically increasing numbers).
SQLite Autoincrement which includes
The AUTOINCREMENT keyword imposes extra CPU, memory, disk space, and disk I/O overhead and should be avoided if not strictly needed. It is usually not needed.
I'd sugggest just using :-
create table Departments(department_id INTEGER PRIMARY KEY,department_name char,department_jobs char);

Web service throws "The value 'null' cannot be parsed as the type 'Guid'." error

I have a system which stores data from an online SQL Server database in local storage. Data records are uploaded and downloaded using a web service. I am using an ADO.Net Entity Data Model in my code.
On some upload requests for one table the routine fails when I try to call it giving an error message "The value 'null' cannot be parsed as the type 'Guid'." This only happens occasionally and I have not worked out how to repeat the problem. I have logged it 80 times in the last month and in that time the routine has been called successfully 1200 times.
I have five fields in the database record for this table that are defined as uniqueidentifiers. Two of these are 'NOT NULL' and the other three are 'NULL'. Here is the 'CREATE TABLE' query showing the guid fields in this table:
CREATE TABLE [dbo].[Circuit](
[CircuitID] [uniqueidentifier] NOT NULL,
[BoardID] [uniqueidentifier] NOT NULL,
[RCDID] [uniqueidentifier] NULL,
[CircuitMasterID] [uniqueidentifier] NULL,
[DeviceID] [uniqueidentifier] NULL,
CONSTRAINT [PK_CircuitGuid] PRIMARY KEY NONCLUSTERED
(
[CircuitID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON)
)
GO
ALTER TABLE [dbo].[Circuit] WITH CHECK ADD CONSTRAINT [FK_Circuit_RCD] FOREIGN KEY([RCDID])
REFERENCES [dbo].[RCD] ([RCDID])
GO
ALTER TABLE [dbo].[Circuit] CHECK CONSTRAINT [FK_Circuit_RCD]
GO
ALTER TABLE [dbo].[Circuit] WITH CHECK ADD CONSTRAINT [FK_CircuitGuid_Board] FOREIGN KEY([BoardID])
REFERENCES [dbo].[Board] ([BoardID])
GO
ALTER TABLE [dbo].[Circuit] CHECK CONSTRAINT [FK_CircuitGuid_Board]
GO
The data uploaded for the guid fields in this table looks like this:
{"__type":"Circuit:#WaspWA","BoardID":"edb5f774-5e5d-490c-860b-73c3419628cf","CircuitID":"e95bbfa3-2af6-49a5-94dd-c98924ec9a62","CircuitMasterID":null,"DeviceID":"daf12fce-675c-46d9-94c4-ed28c63cdf30","RCDID":null}
This record was created on one machine uploaded to the online SQL Server database and then downloaded to another machine.
I have other similar tables in the database which never give any problems. It is just this table which I am getting error messages from. The two fields which are defined as 'NOT NULL' (BoardID and CircuitID) always have data in them and are never null.
Is there something obvious that I have missed here?
The problem was that the value 'null', a string, was being written into my local copy of CircuitMasterID rather than null. So when I tried to write this to SQL it didn't like it. The SQL error message shows null in quotes but I was not sure whether this was because it was a string or because the error message put the value in quotes to delineate it.
The value 'null' had found its way into the CircuitMasterID field because I had written the value null out into some HTML and when this was saved back to the field it became 'null'. I am storing data in local storage and this does not give very good type control. Note to self 'must add better type control'.

Example Needed of Phonegap Sqlite Insert record and then insert other records into a different table

I have it a point that has really got me stuck and help is need
I have two tables
1) Jobs
2) JobNotes
Jobs is made up like the following
ID integer PRIMARY KEY,
Name nvarchar(100) COLLATE NOCASE
etc..
JobNotes is made up like the following
ID integer PRIMARY KEY,
JobID integer .
Notes nvarchar(100) COLLATE NOCASE
FOREIGN KEY ([JobID ]) REFERENCES Jobs,
When i insert a job into the database I need to insert the jobnote and set the JobID to be the id of the job just inserted previously.
Has anyone got examples or know of a method this can be accomplished using phonegap & sqlite.
Best Regards,
Lmac
After doing the insert I get the max id and then pass this into another function that updates the Foreign key.
Its not the most desired way but so far seems to work.

How to merge N SQLite database files into one if db has the primary field?

I have a bunch of SQLite db files, and I need to merge them into one big db files.
How can I do that?
Added
Based on this, I guess those three commands should merge two db into one.
attach './abc2.db' as toMerge;
insert into test select * from toMerge.test
detach database toMerge
The problem is the db has PRIMARY KEY field, and I got this message - "Error: PRIMARY KEY must be unique".
This is the test table for the db.
CREATE TABLE test (id integer PRIMARY KEY AUTOINCREMENT,value text,goody text)
I'm just thinking off my head here... (and probably after everybody else has moved on, too).
Mapping the primary key to "NULL" should yield the wanted result (no good if you use it as foreign key somewhere else, since the key probably exists, but has different contents)
attach './abc2.db' as toMerge;
insert into test select NULL, value, goody from toMerge.test;
detach database toMerge;
actual test:
sqlite> insert into test select * from toMerge.test;
Error: PRIMARY KEY must be unique
sqlite> insert into test select NULL, value, goody from toMerge.test;
sqlite> detach database toMerge;
I'm not 100% sure, but it seems that I should read all the elements and insert the element (except the PRIMARY KEY) one by one into the new data base.

Resources