LoginSignup
0
2

More than 3 years have passed since last update.

PythonのSQLiteで外部キー(Foreign Key)[備忘録]

Last updated at Posted at 2020-07-31

PythonのSQLiteで外部キーを使っていきます

まずPersonテーブルを作ります。

db = "./exsample.db"
con = sqlite3.connect(db)
cur = con.cursor()
table = "Person" # テーブル名
sql = f"""create table {table}(
    id integer primary key autoincrement,
    name text,
    age integer,
)"""
cur.execute(sql) # SQL実行
self.con.commit() # 保存

idprimary keyで主キーにし、autoincrementで自動で振り分けるようにしています。

外部テーブルを作ります。

table = "Memo" # テーブル名
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実行
self.con.commit() # 保存

foreign key(writer_id) references Person(id)に注目です。
ここで、writer_id integerでいったんintegerの項目をつくり、その下で
foreign key(<項目名>) references <繋ぐテーブル名>(<繋ぐテーブルの項目名>)、とします。

0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2