SQL - SQLite - Python - 結合と複数テーブル操作 - みんなでうまくやれないの? - UPDATE, SET, 文字列, 関数, substr, instr
Head First SQL ―頭とからだで覚えるSQLの基本、 Lynn Beighley(著)、 佐藤 直生(監訳)、 松永 多苗子(翻訳)、 オライリージャパンの 8章(結合と複数テーブル操作 - みんなでうまくやれないの?)、p.350(自分で考えてみよう)の解答を求めてみる。
schema3.sql
insert into my_contacts(
interests
) values (
'第1、第2、第3、第4'
);
update my_contacts set interest1 = substr(interests, 1, instr(interests, '、') - 1);
update my_contacts set interests = substr(interests, length(interest1) + 2);
update my_contacts set interest2 = substr(interests, 1, instr(interests, '、') - 1);
update my_contacts set interests = substr(interests, length(interest2) + 2);
update my_contacts set interest3 = substr(interests, 1, instr(interests, '、') - 1);
update my_contacts set interests = substr(interests, length(interest3) + 2);
update my_contacts set interest4 = interests;
コード
sample3.py
#! /usr/bin/env python3
import sqlite3
con = sqlite3.connect('sample.db')
cur = con.cursor()
def p(cur: sqlite3.Cursor, table: str):
cur.execute(
f"""
select * from {table}
"""
)
if (d := cur.description) is not None:
print([t[0] for t in d])
for row in cur.fetchall():
print(row)
p(cur, 'my_contacts')
with open('schema3.sql') as f:
cur.executescript(f.read())
con.commit()
p(cur, 'my_contacts')
cur.close()
con.close()
入出力結果(Terminal, Zsh)
% ./sample3.py
['email', 'birthday', 'first_name', 'last_name', 'interests', 'seeking', 'status', 'profession', 'location', 'gender', 'tel', 'city', 'state', 'interest1', 'interest2', 'interest3', 'interest4']
('jill_anderson@breaknechpizza.com', '1980-09-05', 'ジリアン', 'アンダーソン', 'カヤック乗り、爬虫類', '恋人、友達', '独身', 'テクニカルライター', 'カリフォルニア州パロアルト', 'F', None, None, None, None, None, None, None)
['email', 'birthday', 'first_name', 'last_name', 'interests', 'seeking', 'status', 'profession', 'location', 'gender', 'tel', 'city', 'state', 'interest1', 'interest2', 'interest3', 'interest4']
('jill_anderson@breaknechpizza.com', '1980-09-05', 'ジリアン', 'アンダーソン', '類', '恋人、友達', '独身', 'テクニカルライター', 'カリフォルニア州パロアルト', 'F', None, None, None, 'カヤック乗り', '', '', '類')
(None, None, None, None, '第4', None, None, None, None, None, None, None, None, '第1', '第2', '第3', '第4')
%