LoginSignup
2
4

More than 5 years have passed since last update.

pythonでsqlite3を扱う

Last updated at Posted at 2017-06-22
#coding :utf-8
import sqlite3

dbname='database.db'
conn = sqlite3.connect(dbname)
c = conn.cursor()

#sqlを実行
create_table='''create table users(id int, name vachar(64),
                age int, gender vachar(32))'''
#c.execute(create_table)

# SQL文に値をセットする場合は,Pythonのformatメソッドなどは使わずに,
# セットしたい場所に?を記述し,executeメソッドの第2引数に?に当てはめる値をタプルで渡す
insert = "insert into users(id, name, age, gender) values(?,?,?,?)"
user = (1,"Tato",44,"male")
c.execute(insert,user)

# 一度に複数のSQL文を実行したいときは,タプルのリストを作成した上で
#executemanyメソッドを実行する
users = [
        (2,"shota",54,"female"),
        (3,"nana",40,"female"),
        (4,"FFFF",65535,"male")
]
c.executemany(insert,users)
conn.commit()

#sqlデータを取り出す
select ='select * from users'
for row in c.execute(select):
    print(row)
#sqlを閉じる
conn.close()

2
4
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
2
4