Missing Index Constraint Adding Foreign Key - python

I am trying to define the foreign key in the leaderinfo table as UserID, which is the primary key in the usercredentials table.
USERtable="CREATE TABLE IF NOT EXISTS usercredentials (userID VARCHAR(255),username VARCHAR(255),password VARCHAR(255),stakeholder VARCHAR(255))"
mycursor.execute(USERtable)
LEADERtable="""CREATE TABLE IF NOT EXISTS leaderinfo (leaderID VARCHAR(255),firstname VARCHAR(255),secondname VARCHAR(255),age VARCHAR(255), \
gender VARCHAR(255),ethnicity VARCHAR(255),address VARCHAR(255),postcode VARCHAR(255),telephone VARCHAR(255), \
email VARCHAR(255),userID VARCHAR(255),PRIMARY KEY(leaderID),FOREIGN KEY(userID) REFERENCES usercredentials(userID) on update cascade on delete cascade)"""
Error Code:
mysql.connector.errors.DatabaseError: 1822 (HY000): Failed to add the foreign key constraint. Missing index for constraint 'leaderinfo_ibfk_1' in the referenced table 'usercredentials'

The column you are referencing in the leader table isn't indexed. You can fix this by making the userID column a primary key (I'm going to wrap the SQL here for readability):
USERtable="CREATE TABLE IF NOT EXISTS usercredentials (
userID VARCHAR(255),
username VARCHAR(255),
password VARCHAR(255),
stakeholder VARCHAR(255),
PRIMARY KEY(userID))"

Related

Update on Duplicate key with two columns to check mysql

I am trying to get my head around the 'On Duplicate Key' mysql statement. I have the following table:
id (primary key autoincr) / server id (INT) / member id (INT UNIQUE KEY) / basket (VARCHAR) / shop (VARCHAR UNIQUE KEY)
In this table each member can have two rows, one for each of the shops (shopA and shopB). I want to INSERT if there is no match for both the member id and shop. If there is a match I want it to update the basket to concat the current basket with additional information.
I am trying to use:
"INSERT INTO table_name (server_id, member_id, basket, shop) VALUES (%s, %s, %s, %s) ON DUPLICATE KEY UPDATE basket = CONCAT (basket,%s)"
Currently if there is an entry for the member for shopA when this runs with basket for shopB it adds the basket info to the shopA row instead of creating a new one.
Hope all this makes sense! Thanks in advance!
UPDATE: As requested here is the create table sql statement:
CREATE TABLE table_name ( member_id bigint(20) NOT NULL, server_id bigint(11) NOT NULL, basket varchar(10000) NOT NULL, shop varchar(30) NOT NULL, notes varchar(1000) DEFAULT NULL, PRIMARY KEY (member_id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
In this table each member can have two rows, one for each of the shops
(shopA and shopB)
This means that member_id should not be the primary key of the table because it is not unique.
You need a composite primary key for the columns member_id and shop:
CREATE TABLE table_name (
member_id bigint(20) NOT NULL,
server_id bigint(11) NOT NULL,
basket varchar(10000) NOT NULL,
shop varchar(30) NOT NULL,
notes varchar(1000) DEFAULT NULL,
PRIMARY KEY (member_id, shop)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
See a simplified demo.

Using Python, export SQLite schema

In the SQLite command line, the command .schema can be used to export a database schema in SQL syntax, and that export can be used to rebuild a database of the same structure:
.output folderpath/schema.sql
.schema
Saves the following to a file named "schema.sql":
CREATE TABLE mytable (id INTEGER NOT NULL, name TEXT NOT NULL, date DATETIME, PRIMARY KEY (id), FOREIGN KEY (name) REFERENCES mytable2 (na ...
Can the same output .sql file be achieved using Python's sqlite3 library without a custom function?
There are several questions on Stack Overflow with similar titles, but I didn't find any that are actually trying to get the full schema (they are actually looking for PRAGMA table_info which does not have the CREATE TABLE, etc. statements in the output).
Well. Rewritten the answer above. It that exactly what you need?
import sqlite3
dbname = 'chinook.db'
with sqlite3.connect(dbname) as con:
cursor = con.cursor()
cursor.execute('select sql from sqlite_master')
for r in cursor.fetchall():
print(r[0])
cursor.close()
With the test sqlite3 database I received the following:
CREATE TABLE "albums"
(
[AlbumId] INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
[Title] NVARCHAR(160) NOT NULL,
[ArtistId] INTEGER NOT NULL,
FOREIGN KEY ([ArtistId]) REFERENCES "artists" ([ArtistId])
ON DELETE NO ACTION ON UPDATE NO ACTION
)
CREATE TABLE sqlite_sequence(name,seq)
CREATE TABLE "artists"
(
[ArtistId] INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
[Name] NVARCHAR(120)
)
CREATE TABLE "customers"
(
[CustomerId] INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
[FirstName] NVARCHAR(40) NOT NULL,
[LastName] NVARCHAR(20) NOT NULL,
[Company] NVARCHAR(80),
[Address] NVARCHAR(70),
[City] NVARCHAR(40),
[State] NVARCHAR(40),
[Country] NVARCHAR(40),
[PostalCode] NVARCHAR(10),
[Phone] NVARCHAR(24),
[Fax] NVARCHAR(24),
[Email] NVARCHAR(60) NOT NULL,
[SupportRepId] INTEGER,
FOREIGN KEY ([SupportRepId]) REFERENCES "employees" ([EmployeeId])
ON DELETE NO ACTION ON UPDATE NO ACTION
)
CREATE TABLE "employees"
(
[EmployeeId] INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
[LastName] NVARCHAR(20) NOT NULL,
[FirstName] NVARCHAR(20) NOT NULL,
[Title] NVARCHAR(30),
[ReportsTo] INTEGER,
[BirthDate] DATETIME,
[HireDate] DATETIME,
[Address] NVARCHAR(70),
[City] NVARCHAR(40),
[State] NVARCHAR(40),
[Country] NVARCHAR(40),
[PostalCode] NVARCHAR(10),
[Phone] NVARCHAR(24),
[Fax] NVARCHAR(24),
[Email] NVARCHAR(60),
FOREIGN KEY ([ReportsTo]) REFERENCES "employees" ([EmployeeId])
ON DELETE NO ACTION ON UPDATE NO ACTION
)
CREATE TABLE "genres"
(
[GenreId] INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
[Name] NVARCHAR(120)
)
CREATE TABLE "invoices"
(
[InvoiceId] INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
[CustomerId] INTEGER NOT NULL,
[InvoiceDate] DATETIME NOT NULL,
[BillingAddress] NVARCHAR(70),
[BillingCity] NVARCHAR(40),
[BillingState] NVARCHAR(40),
[BillingCountry] NVARCHAR(40),
[BillingPostalCode] NVARCHAR(10),
[Total] NUMERIC(10,2) NOT NULL,
FOREIGN KEY ([CustomerId]) REFERENCES "customers" ([CustomerId])
ON DELETE NO ACTION ON UPDATE NO ACTION
)
CREATE TABLE "invoice_items"
(
[InvoiceLineId] INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
[InvoiceId] INTEGER NOT NULL,
[TrackId] INTEGER NOT NULL,
[UnitPrice] NUMERIC(10,2) NOT NULL,
[Quantity] INTEGER NOT NULL,
FOREIGN KEY ([InvoiceId]) REFERENCES "invoices" ([InvoiceId])
ON DELETE NO ACTION ON UPDATE NO ACTION,
FOREIGN KEY ([TrackId]) REFERENCES "tracks" ([TrackId])
ON DELETE NO ACTION ON UPDATE NO ACTION
)
CREATE TABLE "media_types"
(
[MediaTypeId] INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
[Name] NVARCHAR(120)
)
CREATE TABLE "playlists"
(
[PlaylistId] INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
[Name] NVARCHAR(120)
)
CREATE TABLE "playlist_track"
(
[PlaylistId] INTEGER NOT NULL,
[TrackId] INTEGER NOT NULL,
CONSTRAINT [PK_PlaylistTrack] PRIMARY KEY ([PlaylistId], [TrackId]),
FOREIGN KEY ([PlaylistId]) REFERENCES "playlists" ([PlaylistId])
ON DELETE NO ACTION ON UPDATE NO ACTION,
FOREIGN KEY ([TrackId]) REFERENCES "tracks" ([TrackId])
ON DELETE NO ACTION ON UPDATE NO ACTION
)
None
CREATE TABLE "tracks"
(
[TrackId] INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
[Name] NVARCHAR(200) NOT NULL,
[AlbumId] INTEGER,
[MediaTypeId] INTEGER NOT NULL,
[GenreId] INTEGER,
[Composer] NVARCHAR(220),
[Milliseconds] INTEGER NOT NULL,
[Bytes] INTEGER,
[UnitPrice] NUMERIC(10,2) NOT NULL,
FOREIGN KEY ([AlbumId]) REFERENCES "albums" ([AlbumId])
ON DELETE NO ACTION ON UPDATE NO ACTION,
FOREIGN KEY ([GenreId]) REFERENCES "genres" ([GenreId])
ON DELETE NO ACTION ON UPDATE NO ACTION,
FOREIGN KEY ([MediaTypeId]) REFERENCES "media_types" ([MediaTypeId])
ON DELETE NO ACTION ON UPDATE NO ACTION
)
CREATE INDEX [IFK_AlbumArtistId] ON "albums" ([ArtistId])
CREATE INDEX [IFK_CustomerSupportRepId] ON "customers" ([SupportRepId])
CREATE INDEX [IFK_EmployeeReportsTo] ON "employees" ([ReportsTo])
CREATE INDEX [IFK_InvoiceCustomerId] ON "invoices" ([CustomerId])
CREATE INDEX [IFK_InvoiceLineInvoiceId] ON "invoice_items" ([InvoiceId])
CREATE INDEX [IFK_InvoiceLineTrackId] ON "invoice_items" ([TrackId])
CREATE INDEX [IFK_PlaylistTrackTrackId] ON "playlist_track" ([TrackId])
CREATE INDEX [IFK_TrackAlbumId] ON "tracks" ([AlbumId])
CREATE INDEX [IFK_TrackGenreId] ON "tracks" ([GenreId])
CREATE INDEX [IFK_TrackMediaTypeId] ON "tracks" ([MediaTypeId])
CREATE TABLE sqlite_stat1(tbl,idx,stat)

ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails That I can't fix

I am getting this error :
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint
fails (\`GTFS\`.\`#sql-37d_16\`, CONSTRAINT \`#sql-37d_16_ibfk_1\` FOREIGN KEY
(\`service_id\`) REFERENCES \`calendar\` (\`service_id\`))
I'm trying to create my database tables with python , this is what i've tried :
mycursor.execute("CREATE TABLE IF NOT EXISTS routes(route_id varchar(3) PRIMARY KEY, agency_id varchar(2) ,route_short_name varchar(20) ,route_long_name varchar(50) ,route_desc varchar(30) ,route_type varchar(30) ,route_url varchar(30) ,route_color varchar(30) ,route_text_color varchar(30)) ")
mycursor.execute("CREATE TABLE IF NOT EXISTS calendar (service_id varchar(4) PRIMARY KEY,monday varchar(4) ,tuesday varchar(4) ,wednesday varchar(4) ,thursday varchar(4) ,friday varchar(4) ,saturday varchar(4) ,sunday varchar(4) ,start_date varchar(8) ,end_date varchar(8)) ")
mycursor.execute("CREATE TABLE IF NOT EXISTS trips (route_id varchar(3) ,service_id varchar(4) ,trip_id varchar(6) PRIMARY KEY,trip_headsign varchar(20) ,trip_short_name varchar(3) ,direction_id varchar(1) ,block_id varchar(1) ,shape_id varchar(5) )")
mycursor.execute("ALTER TABLE trips ADD FOREIGN KEY (service_id) REFERENCES calendar(service_id); ")
mycursor.execute("ALTER TABLE trips ADD FOREIGN KEY (route_id) REFERENCES routes(route_id); ")
I'm expecting to insert into my table some data provided in a list but i always get this error in my terminal
Because some values for trips.service_id column don't exist in the parent(calendar) table for the common column service_id.
You may try to insert those values by such a insert statement :
insert into calendar(...,service_id,...)
select ...,service_id,...
from trips t
where not exists ( select 0 from calendar where service_id=t.service_id );
before adding the constraint by
ALTER TABLE trips ADD FOREIGN KEY (service_id) REFERENCES calendar(service_id);

Creating tables in MySQL in Python 3.4

I am running a server through Apache using Python 3.4 as a cgi and a MySQL database server on Windows 10. When I try to run my function for creating the database I get the error:
DatabaseError: 1005 (HY000): Can't create table `testdb`.`studentexam` (errno: 150
"Foreign key constraint is incorrectly formed")
The function for creating the database
import mysql.connector as conn
#connect to server
db=conn.connect(host="localhost",user="root",password="")
cursor=db.cursor()
#create database
cursor.execute("""CREATE DATABASE IF NOT EXISTS Testdb""")
db.commit()
#use database
cursor.execute("""USE Testdb""")
db.commit()
#create Teacher table
cursor.execute("""CREATE TABLE IF NOT EXISTS Teacher(
TeacherUsername VARCHAR(255) PRIMARY KEY,
TeacherPassword TEXT)""")
db.commit()
#create student table
cursor.execute("""CREATE TABLE IF NOT EXISTS Student(
StudentNo INT PRIMARY KEY,
StudentSurname TEXT,
StudentForename TEXT,
StudentTeacher VARCHAR(255),
StudentPassword TEXT,
FOREIGN KEY(StudentTeacher) REFERENCES Teacher(TeacherUsername))""")
db.commit()
#create exam table
cursor.execute("""CREATE TABLE IF NOT EXISTS Exam(
TestName VARCHAR(255) PRIMARY KEY,
TestTotalMarks TEXT,
Teacher VARCHAR(255),
FOREIGN KEY(Teacher) REFERENCES Teacher(TeacherUsername))""")
db.commit()
#create StudentExam table
cursor.execute("""CREATE TABLE IF NOT EXISTS StudentExam(
TestName VARCHAR(255),
StudentID INT,
StudentTotalMarks INT,
PRIMARY KEY(TestName,StudentID),
FOREIGN KEY(TestName) REFERENCES Exam(TestName),
FOREIGN KEY(StudentID) REFERENCES Student(StudentID))""")
db.commit()
#create ExamSection table
cursor.execute("""CREATE TABLE IF NOT EXISTS ExamSection(
TestName VARCHAR(255),
SectionID INT,
PRIMARY KEY(TestName,SectionID),
FOREIGN KEY(TestName) REFERENCES Exam(TestName),
FOREIGN KEY(SectionID) REFERENCES Section(SectionID))""")
db.commit()
#create Section table
cursor.execute("""CREATE TABLE IF NOT EXISTS Section(
SectionID INT PRIMARY KEY,
SectionName TEXT,
SectionTotalMarks INT)""")
db.commit()
#create Question table
cursor.execute("""CREATE TABLE IF NOT EXISTS Question(
QuestionID INT PRIMARY KEY,
SectionID VARCHAR(255),
Image TEXT,
Question TEXT,
PossibleAnswer TEXT,
CorrectAnswer TEXT,
QuestionType TEXT,
FOREIGN KEY(SectionID) REFERENCES Section(SectionID))""")
db.commit()
#create QuestionResults Table
cursor.execute("""CREATE TABLE IF NOT EXISTS QuestionResults(
QuestionID INT,
StudentID INT,
SectionID VARCHAR(255),
StudentAnswer TEXT,
PRIMARY KEY(QuestionID,StudentID),
FOREIGN KEY(QuestionID) REFERENCES Question(QuestionID)
FOREIGN KEY(StudentID) REFERENCES Student(StudentID))""")
db.commit()
#create Revision table
cursor.execute("""CREATE TABLE IF NOT EXISTS Revision(
RevisionID INT PRIMARY KEY,
RevisionSheet TEXT,
TeacherUsername VARCHAR(255),
FOREIGN KEY(TeacherUsername) REFERENCES Teacher(TeacherUsername))""")
db.commit()
#create StudentRevition table
cursor.execute("""CREATE TABLE IF NOT EXISTS StudentRevision(
RevisionID INT,
StudentID INT,
PRIMARY KEY(RevisionID,StudentID),
FOREIGN KEY(RevisionID) REFERENCES Revision(RevisionID),
FOREIGN KEY(StudentID) REFERENCES Student(StudentID))""")
db.commit()
#create StudentResults table
cursor.execute("""CREATE TABLE IF NOT EXISTS StudentResults(
SectionID VARCHAR(255),
StudentID INT,
StudentSectionMarks INT,
PRIMARY KEY(SectionID,StudentID),
FOREIGN KEY(SectionID) REFERENCES Section(SectionID),
FOREIGN KEY(StudentID) REFERENCES Student(StudentID))""")
db.commit()
cursor.close()
EDIT: I Changed StudentNo to StudentID and now get the error:
DatabaseError: 1005 (HY000): Can't create table `testdb`.`examsection` (errno: 150
"Foreign key constraint is incorrectly formed")
Change this:
#create student table
cursor.execute("""CREATE TABLE IF NOT EXISTS Student(
StudentNo INT PRIMARY KEY,
StudentSurname TEXT,
StudentForename TEXT,
StudentTeacher VARCHAR(255),
StudentPassword TEXT,
FOREIGN KEY(StudentTeacher) REFERENCES Teacher(TeacherUsername))""")
db.commit()
to this:
#create student table
cursor.execute("""CREATE TABLE IF NOT EXISTS Student(
StudentID INT PRIMARY KEY,
StudentSurname TEXT,
StudentForename TEXT,
StudentTeacher VARCHAR(255),
StudentPassword TEXT,
FOREIGN KEY(StudentTeacher) REFERENCES Teacher(TeacherUsername))""")
db.commit()
When creating StudentExam, you are referencing Student.StudentId which doesn't exist. It looks like you rather want to reference Student.StudentNo.
edit:
When you create ExamSection, you reference the Section table, which doesn't exist yet. Move the Section creation state up so that it runs and commits before you create ExamSection.

How to create unique rows in a table?

I`m just started to learn SQLite. I use python.
The question is how to create rows in tables, so that they are uniqe by name and how to use (extract) id1 and id2 to insert them into a separate table.
import sqlite3
conn = sqlite3.connect('my.db')
c = conn.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS table1(
id1 integer primary key autoincrement, name)''')
c.execute('''CREATE TABLE IF NOT EXISTS table2(
id2 integer primary key autoincrement, name)''')
c.execute('CREATE TABLE IF NOT EXISTS t1_t2(id1, id2)') # many-to-many
conn.commit()
conn.close()
conn = sqlite3.connect('my.db')
c = conn.cursor()
c.execute('INSERT INTO table1 VALUES (null, "Sue Monk Kidd")')
c.execute('INSERT INTO table2 VALUES (null, "The Invention of Wings")')
#c.execute('INSERT INTO t1_t2 VALUES (id1, id2)')
c.execute('INSERT INTO table1 VALUES (null, "Colleen Hoover")')
c.execute('INSERT INTO table2 VALUES (null, "Maybe Someday")')
#c.execute('INSERT INTO t1_t2 VALUES (id1, id2)')
Thanks.
I think you have some problems with the table creation. I doubt that it worked, because the name columns don't have a type. They should probably be varchar of some length. The JOIN table definition isn't right, either.
CREATE TABLE IF NOT EXISTS table1 (
id1 integer primary key autoincrement,
name varchar(80)
);
CREATE TABLE IF NOT EXISTS table2 (
id2 integer primary key autoincrement,
name varchar(80)
);
CREATE TABLE IF NOT EXISTS t1_t2 (
id1 integer,
id2 integer,
primary key(id1, id2),
foreign key(id1) references table1(id1),
foreign key(id2) references table2(id2)
);
I would not create the tables in code. Script them, execute in the SQLite admin, and have the tables ready to go when your Python app runs.
I would think much harder about your table names if these are more than examples.
I found the problem of unique names on unique column problem.
Actually, I should change INSERT to INSERT OR IGNORE
import sqlite3
conn = sqlite3.connect('my.db')
c = conn.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS table1(
id1 integer primary key autoincrement, name TEXT unique)''')
c.execute('''CREATE TABLE IF NOT EXISTS table2(
id2 integer primary key autoincrement, name TEXT unique)''')
c.execute('CREATE TABLE IF NOT EXISTS t1_t2(id1, id2)') # many-to-many
conn.commit()
conn.close()
conn = sqlite3.connect('my.db')
c = conn.cursor()
c.execute('INSERT OR IGNORE INTO table1 VALUES (null, "Sue Monk Kidd")')
c.execute('INSERT OR IGNORE INTO table2 VALUES (null, "The Invention of Wings")')

Categories

Resources