Foreign Key in Python SQLite [Note]

I will use foreign keys with SQLite in Python

First, create a Person table.

db = "./exsample.db"
con = sqlite3.connect(db)
cur = con.cursor()
table = "Person" #table name
sql = f"""create table {table}(
    id integer primary key autoincrement,
    name text,
    age integer,
)"""
cur.execute(sql) #SQL execution
self.con.commit() #Save

ʻId is used as the primary key with primary key, and is automatically sorted with ʻautoincrement.

Create an external table.

table = "Memo" #table name
sql = f"""create table {table}(
    id integer primary key autoincrement,
    title text,
    content text,
    writer_id integer,
    foreign key(writer_id) references Person(id)
)"""
cur.execute(sql) #SQL execution
self.con.commit() #Save

Note the foreign key (writer_id) references Person (id). Here, once create an item of ʻintegrar with writer_id integer, and under that foreign key () references (),`.

Recommended Posts

Foreign Key in Python SQLite [Note]
Sqlite in python
Key input in Python
Key input in Python
Python Input Note in AtCoder
Implemented List and Bool in Python and SQLite3 (personal note)
[Note] Project Euler in Python (Problem 1-22)
How to use SQLite in Python
Write foreign key constraints in Django
Python note
In python + sqlite3 "OperationalError: no such column:"
Trying to handle SQLite3 with Python [Note]
Quadtree in Python --2
Python in optimization
CURL in python
Python study note_002
Metaprogramming in Python
Python 3.3 in Anaconda
Python programming note
Geocoding in python
SendKeys in Python
[Python] Learning Note 1
Meta-analysis in Python
Unittest in python
Python study note_004
Epoch in Python
Discord in Python
Sudoku in Python
DCI in Python
quicksort in python
N-Gram in Python
Programming in python
Plink in Python
Constant in python
Lifegame in Python.
FizzBuzz in Python
StepAIC in Python
[Note] openCV + python
N-gram in python
LINE-Bot [0] in Python
Csv in python
Disassemble in Python
Reflection in Python
Constant in python
nCr in Python.
format in python
Scons in Python3
Puyo Puyo in python
python in virtualenv
PPAP in Python
Quad-tree in Python
Python beginner's note
Reflection in Python
Chemistry in Python
Hashable in python
DirectLiNGAM in Python
LiNGAM in Python
Flatten in python
flatten in python
3 ways to parse time strings in python [Note]
A note on optimizing blackbox functions in Python