(Python, sqlite3) Building relational database? - python

I am trying to create a relational database in python with sqlite3. I am a little fussy on how to connect the tables in the database so that one entity connects to another via the second table. I want to be able to make a search on a persons name via a webpage and then find the parents related to that person. Im not sure if I need two tables or three.
This is how my code looks like right now:
class Database:
'''Initiates the database.'''
def __init__(self):
self.db = sqlite3.connect('family2.db')
def createTable(self):
r = self.db.execute('''
CREATE TABLE IF NOT EXISTS family2 (
id INTEGER PRIMARY KEY ASC AUTOINCREMENT,
fname TEXT,
sname TEXT,
birthdate TEXT,
deathdate TEXT,
mother TEXT,
father TEXT
)''')
self.db.commit()
g = self.db.execute('''CREATE TABLE IF NOT EXISTS parents(
id INTEGER PRIMARY KEY ASC AUTOINCREMENT,
mother TEXT,
father TEXT)''')
self.db.commit()
b = self.db.execute('''CREATE TABLE IF NOT EXISTS relations(
id INTEGER PRIMARY KEY ASC AUTOINCREMENT,
family2,
parents TEXT
)''')
self.db.commit()
Thanks in advance!

You don't need multiple tables; you can store the IDs of the parents in the table itself:
CREATE TABLE persons(
id INTEGER PRIMARY KEY,
name TEXT,
mother_id INT,
father_id INT
);
You can then find the mother of a person that is identified by its name with a query like this:
SELECT *
FROM persons
WHERE id = (SELECT mother_id
FROM persons
WHERE name = '...')

Related

Attempted to autoincrement an integer value but returend null, how do I fix?

tblcustomer = """ CREATE TABLE IF NOT EXISTS Customer
(
CustomerID INT,
CustomerName TEXT,
Address TEXT,
Postcode TEXT,
EmailAddress TEXT,
primary key(CustomerID AUTOINCREMENT)
)"""
cursor.execute(tblcustomer)
connection.commit()
This is my table (I'm using sqlite3), but it returns 'null' to the table values. For my user inputs I just asked for the other 4 values and inserted them into the table, omitting 'CustomerID'. How do I fix it so it actually autoincrements?
Here's how you can modify your table to include an AUTOINCREMENT column for the CustomerID field:
CREATE TABLE IF NOT EXISTS Customer(
CustomerID INTEGER PRIMARY KEY AUTOINCREMENT,
CustomerName TEXT,
Address TEXT,
Postcode TEXT,
EmailAddress TEXT)

How can I list the data of foreign keys linked to the id of the table?

What I want to do is create 4 interconnected progressive category classes.I don't know if the method I did is correct. Unfortunately I have been reading the document for days. but I haven't made much progress
Over the 'company' class how can I query all data belonging to the 'DepartmentalUnit' class?
create_table_company= '''CREATE TABLE company(
ID SERIAL PRIMARY KEY ,
NAME VARCHAR NOT NULL ,
); '''
create_table_department = '''CREATE TABLE department (
ID SERIAL PRIMARY KEY ,
NAME VARCHAR NOT NULL ,
company_id BIGINT,
FOREIGN KEY(company_id) REFERENCES COMPANY(id)); '''
create_table_department_unit = '''CREATE TABLE department_unit(
ID SERIAL PRIMARY KEY ,
NAME VARCHAR NOT NULL ,
department_id BIGINT,
FOREIGN KEY(department_id) REFERENCES DEPARTMENT(id));
create_table_department_unit_categroy = '''CREATE TABLE department_unit_category(
ID SERIAL PRIMARY KEY ,
NAME VARCHAR NOT NULL ,
department_unit_id BIGINT,
FOREIGN KEY(department_unit_id) REFERENCES DEPARTMENT_UNİT(id));
Something like this:
SELECT
c.id, c.name, du.*
FROM
company AS c
JOIN
department AS d
ON
c.id = d.company_id
JOIN
department_unit AS du
ON
du.department_id = d.id
;
UPDATE
The above query works to get the department_unit information by connecting the tables by their common fields. In this case the company table finds the department information for each company by using the company_id field in department that links back to a company. Once the departments for a company are found the department units for each department is found by using the department_id field in department_unit to link back to the department table. The end result is a chain that connects a company to its department units.

sqlite3.IntegrityError: Datatype Missmatch

When I run my code, i am getting an error saying "sqlite3.IntegrityError: Datatype Mismatch". I believe it's something to do with database but I can't seem to find the error. I checked if i have let a foreign key of a particular datatype reference an attribute of a different datatype but still can't find the error. Here is my database:
import sqlite3
connection = sqlite3.connect('database.db')
cursor = connection.cursor()
cursor.execute("""CREATE TABLE IF NOT EXISTS tblCustomer (
customerID TEXT (6),
firstName TEXT (10),
secondName TEXT (15),
dob DATE,
address TEXT,
telephone INT (11),
primary key (customerID)
)""")
tblCustomer = []
cursor.execute("""CREATE TABLE IF NOT EXISTS tblEmployee (
employeeID TEXT (6),
firstName TEXT (10),
secondName TEXT (15),
dob DATE,
address TEXT,
telephone INT (11),
gender TEXT,
role TEXT,
salary INT,
primary key (employeeID)
)""")
tblEmployee = []
cursor.execute("""CREATE TABLE IF NOT EXISTS tblBooking (
bookingID TEXT (6),
checkInDate DATE,
checkOutDate DATE,
numberOfOccupants INT,
customerID TEXT,
roomID TEXT,
primary key (bookingID),
foreign key (customerID) REFERENCES tblCustomer(customerID),
foreign key (roomID) REFERENCES tblRoomAllocation(roomID)
)""")
tblBooking = []
cursor.execute("""CREATE TABLE IF NOT EXISTS tblRoomAllocation (
roomID TEXT (6),
roomType TEXT (20),
DateAdded DATE,
DateVacated DATE,
housekeepingID TEXT,
primary key (roomID),
foreign key (housekeepingID) REFERENCES tblHousekeeping(housekeepingID)
)""")
tblRoomAllocation = []
cursor.execute("""CREATE TABLE IF NOT EXISTS tblHousekeeping (
housekeepingID TEXT (6),
dob DATE,
assignedTo TEXT (20),
primary key (housekeepingID)
)""")
tblHousekeeping = []
cursor.execute("""CREATE TABLE IF NOT EXISTS tblPayment (
paymentID TEXT (6),
dob DATE,
amountPaid CURRENCY,
customerID TEXT (6),
primary key (paymentID),
foreign key (customerID) REFERENCES tblCustomer(customerID)
)""")
tblPayment = []
cursor.execute("""CREATE TABLE IF NOT EXISTS tblOrder(
orderID TEXT (6),
price CURRENCY,
customerID TEXT (6),
treatmentID TEXT (6),
primary key (orderID),
foreign key (customerID) REFERENCES tblCustomer(customerID),
foreign key (treatmentID) REFERENCES tblTreatment(treatmentID)
)""")
tblOrder = []
cursor.execute("""CREATE TABLE IF NOT EXISTS tblTreatment(
treatmentID TEXT (6),
treatmentType TEXT (20),
extras TEXT(20),
employeeID TEXT (6),
primary key (treatmentID),
foreign key (employeeID) REFERENCES tblEmployee(employeeID)
)""")
tblTreatment = []
cursor.execute("""CREATE TABLE IF NOT EXISTS tblUser (
userID TEXT (6),
firstName TEXT (10),
secondName TEXT (15),
username VARCHAR(20),
password VARCHAR (20),
primary key (userID)
)""")
tblUser = []
SQLite does not support DATE data type.
See what is supported:
https://www.sqlite.org/datatype3.html
Try using an INTEGER (store unix timestamp), or a TEXT (for iso8601 date).

SQLite Copying data to second table from first table

I have two tables created from below query in SQLite:
CREATE TABLE people (
id integer unique primary key,
first_name text,
middle_name text,
last_name text,
email text,
phone text
);
CREATE TABLE companies (
id integer unique primary key,
name text,
url text,
contact integer,
FOREIGN KEY(contact) REFERENCES people(id)
);
I have all the data available in the first table, but I want to popup id in second table same as id in the first table.name in the companies table is concatenated string of first_name text,middle_name,last_name in people table.
I want something like "UPDATE companies SET contact = (SELECT people.id FROM people WHERE companies.name = people.first_name || "," || "people.second_name"; it will be great if I can show the string in people table is the subset of string in companies table
I am a beginner in python and SQlite both.

SQlite Update Record through Foreign Key

for my code I need to update a record through a users ID number. When the values are entered into an entry box for Exercise and Weight a button is clicked to update the record. Exercises is the first table which has a foreign key ID which is linked to MemberID in the memb table. I have created an UPDATE query for this, this is the code:
def Update(self):
global MemberID
connection = sqlite3.connect(r"E:\TESTING\Program\Accounts.db")
cursor = connection.cursor()
Exercise = self.Exercises.get()
Weight = self.Weights.get()
MemberID = self.ent_MemberID.get()
List = [Exercise, Weight]
cursor.execute("UPDATE Exercises SET Exercise=?, Weight=? WHERE ID = (SELECT MemberID FROM memb WHERE MemberID = ?);",(Exercise, Weight, MemberID))
connection.commit()
It doesn't show any errors but is not entering the data into the table. This is the code I used to create the Exercises table:
CREATE TABLE `Exercises` (
`Exercise` TEXT,
`Weight` INTEGER,
`Reps` INTEGER,
`Sets` INTEGER,
`ID` INTEGER,
PRIMARY KEY(`ID`),
FOREIGN KEY(`ID`) REFERENCES `memb`(`MemberID`)
);

Categories

Resources