sqlite
is a standard module included in Python
. You can ʻimport` without installing.
import sqlite3
db = "./exsample.db" #Path to database
con = sqlite3.connect(db) #connect
cur = con.cursor()
table = "Friend" #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 assigned with ʻautoincrement
.
table = "Friend" #table name
sql = f"""create table if not exists {table}(
id integer primary key autoincrement,
name text,
age integer,
)"""
cur.execute(sql) #SQL execution
self.con.commit() #Save
Enter ʻif not exists`.
old_table = "Friend" #Old table name
new_table = "NewFriend" #New table name
sql = f"alter table {old_table} rename to {new_table}"
cur.execute(sql) #SQL execution
self.con.commit() #Save
table = "NewFriend" #The table you want to delete
sql = f"drop table {table}"
cur.execute(sql) #SQL execution
self.con.commit() #Save
Model name | information |
---|---|
NULL | Null value |
INTEGER | Signed integer. 1, 2, 3, 4, 6,or 8 bytes |
REAL | Floating point number. Store in 8 bytes |
TEXT | text. UTF-8, UTF-16BE or UTF-16-Stored in one of LE |
BLOB | Store input data as it is |
table = "Friend" #table name
sql = f"insert into {table} (name, age) values ('Jiro', 20)"
cur.execute(sql) #SQL execution
self.con.commit() #Save
Or
table = "Friend" #table name
sql = f"insert into {table} (name, age) values (?, ?)"
data = ("Jiro", 20)
cur.execute(sql, data) #SQL execution
self.con.commit() #Save
It can be inserted by setting it to ?
And inserting a tuple in the second argument.
Try converting Jiro to Taro
table = "Friend" #table name
id = 1 #ID of the record you want to edit
sql = f"update {table} set name='Taro' where id={id}"
cur.execute(sql) #SQL execution
self.con.commit() #Save
table = "Friend" #table name
id = 1 #ID of the record to delete
sql = f"delete from {table} where id={id}"
cur.execute(sql) #SQL execution
self.con.commit() #Save
Recommended Posts