I am new to sqlite3, need your help to join these two table, I need to joint the team id between a coach and the teams table, but when compiling it tells me that there is a problem with teamID in the coach table.
Any idea where is my mistake?
def creationTeamDB():
with sqlite3.connect("teams.db") as db1:
cursor = db1.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS team (
teamID INTEGER PRIMARY KEY,
teamName VARCHAR(20) NOT NULL
)
''')
def creationCoachDB():
with sqlite3.connect("coachs.db") as db2:
cursor = db2.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS coach (
coachID INTEGER PRIMARY KEY,
coachName VARCHAR(20) NOT NULL
teamID INTEGER
)
''')
Thanks in advance, :)
G.B
You missed the comma in the second query
CREATE TABLE IF NOT EXISTS coach (
coachID INTEGER PRIMARY KEY,
coachName VARCHAR(20) NOT NULL,
teamID INTEGER
)
Related
i have an sql insert query that take values from user input and also insert the ID from another table as foreign key. for this is write the below query but it seems not working.
Status_type table
CREATE TABLE status_type (
ID int(5) NOT NULL,
status varchar(50) NOT NULL
);
info table
CREATE TABLE info (
ID int(11) NOT NULL,
name varchar(50), NULL
nickname varchar(50), NULL
mother_name varchar(50), NULL
birthdate date, NULL
status_type int <==this must be the foreign key for the status_type table
create_date date
);
for the user he has a dropdownlist that retrieve the value from the status_type table in order to select the value that he want to insert into the new record in the info table
where as the info table take int Type because i want to store the ID of the status_type and not the value
code:
query = '''
INSERT INTO info (ID,name,nickname,mother_name,birthdate,t1.status_type,created_date)
VALUES(?,?,?,?,?,?,?)
select t2.ID
from info as t1
INNER JOIN status_type as t2
ON t2.ID = t1.status_type
'''
args = (ID,name,nickname,mother_name,db,status_type,current_date)
cursor = con.cursor()
cursor.execute(query,args)
con.commit()
st.success('Record added Successfully')
the status_type field take an INT type (the ID of the value from another table ).
So when the user insert it insert the value.
What i need is to convert this value into its corresponding ID and store the ID
based on the answer of #Mostafa NZ I modified my query and it becomes like below :
query = '''
INSERT INTO info (ID,name,nickname,mother_name,birthdate,status_type,created_date)
VALUES(?,?,?,?,?,(select status_type.ID
from status_type
where status = ?),?)
'''
args = (ID,name,nickname,mother_name,db,status_type,current_date)
cursor = con.cursor()
cursor.execute(query,args)
con.commit()
st.success('Record added Successfully')
When creating a record, you can do one of these ways.
Receive as input from the user
Specify a default value for the field
INSERT INTO (...) VALUES (? ,? ,1 ,? ,?)
Use a select in the INSERT
INSERT INTO (...) VALUES (? ,? ,(SELECT TOP 1 ID FROM status_type ODER BY ID) ,? ,?)
When INSERT data, you can only enter the names of the destination table fields. t1.status_type is wrong in the following line
INSERT INTO info (ID,name,nickname,mother_name,birthdate,t1.status_type,created_date)
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.
i have this part of a python script to create tables into a mysql db
#Product
TABLES['product'] = (
"CREATE TABLE product"
"(prod_id smallint,"
"name varchar(255),"
"price int,"
"constraint pk_prod_id primary key (prod_id)"
");")
#Sales
TABLES['sales'] = (
"CREATE TABLE sales"
"(sales_id smallint,"
"name varchar(255),"
"quantity int,"
"buy_id smallint,"
"date DATE,"
"constraint pk_sales_id primary key (sales_id,name)"
");")
#Purchase
TABLES['purchase'] = (
"CREATE TABLE purchase"
"(purchase_id smallint,"
"name varchar(255),"
"quantity int,"
"sup_id smallint,"
"date DATE,"
"constraint pk_purchase_id primary key (purchase_id,name)"
");")
# Adding foreign key
query = 'ALTER TABLE sales ADD foreign key(buy_id) references buyers(buy_id)'
cursor.execute(query)
query = 'ALTER TABLE purchase ADD foreign key(sup_id) references suppliers(sup_id)'
cursor.execute(query)
Until here it works ok, but here is the main problem.
query = 'ALTER TABLE sales ADD foreign key(name) references product(name)'
cursor.execute(query)
query = 'ALTER TABLE purchase ADD foreign key(name) references product (name)'
cursor.execute(query)
the error code is 1215, so can't add foreign keys
It works if i do this
query = ('ALTER TABLE sales ADD foreign key(prod_id) references product(prod_id)')
cursor.execute(query)
query = ('ALTER TABLE purchase ADD foreign key(prod_id) references product(prod_id)')
cursor.execute(query)
but i prefer to work with name and not with prod_id because it's a mess.
how can i solve this issues ? i tried with int type, but i don't like this solution, moreover i have to rewrite a lot of query.
Make the table product like this with KEY (name)
#Product
TABLES['product'] = (
"CREATE TABLE product"
"(prod_id smallint,"
"name varchar(255),"
"price int,"
"constraint pk_prod_id primary key (prod_id),"
"KEY (name)"
");")
And you can without probems add a foreign key to product name
thank you, it works.
But the previous query now doesn't work anymore
for istance i could do this;
cursor = cnx.cursor()
date = str(input('insert a date in yyyy-mm-dd :'))
query = "SELECT SUM(DISTINCT p.price*s.quantity),COUNT(p.price*s.quantity) FROM product p JOIN sales s ON p.name = s.name WHERE s.date > "
cursor.execute(query+"'"+date+"'")
for i,j in cursor:
print("Number of sales {}\nMoney earned {}".format(j,i))
and the out put was this
insert a date in yyyy-mm-dd :2019-06-03
Number of sales 5
Money earned 12750
now this doesn't work anymore.
How can I print out the schema of all tables using sqlalchemy?
This is how I do it using SQLite3: I run an SQL to print out the schema of all tables in the database:
import sqlite3
conn = sqlite3.connect("example.db")
cur = conn.cursor()
rs = cur.execute(
"""
SELECT name, sql FROM sqlite_master
WHERE type='table'
ORDER BY name;
""")
for name, schema, *args in rs:
print(name)
print(schema)
print()
With output that can look like this:
albums
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
)
artists
CREATE TABLE "artists"
(
[ArtistId] INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
[Name] NVARCHAR(120)
)
Is there a way to do it with pure sqlalchemy api calls, something better than this?
metadata = sqlalchemy.MetaData()
metadata.reflect(engine)
insp = sqlalchemy.inspect(engine)
for table_name in metadata.tables:
print(table_name)
for column in insp.get_columns(table_name):
for name,value in column.items():
print(' ', end='')
if value:
field = name if value in [True, 'auto'] else value
print(field, end=' ')
print()
Output:
albums
AlbumId INTEGER autoincrement primary_key
Title NVARCHAR(160) autoincrement
ArtistId INTEGER autoincrement
artists
ArtistId INTEGER autoincrement primary_key
Name NVARCHAR(120) nullable autoincrement
This bit in the SQLAlchemy docs may help: they suggest doing this:
def dump(sql, *multiparams, **params):
print(sql.compile(dialect=engine.dialect))
engine = create_engine('postgresql://', strategy='mock', executor=dump)
metadata.create_all(engine, checkfirst=False)
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 = '...')