0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

SQLite3でデータベースを作成するPythonコード

Posted at

SQLite3でデータベースを作成するPythonコード

import sqlite3

データベースファイル名

dbname = 'mydatabase.db'

データベースに接続 (ファイルが存在しない場合は新規作成)

conn = sqlite3.connect(dbname)

カーソルオブジェクトを作成

cur = conn.cursor()

テーブルを作成 (既に存在する場合は何もしない)

cur.execute('''
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
age INTEGER,
email TEXT UNIQUE
)
''')

変更をコミット (データベースに反映)

conn.commit()

接続を閉じる

conn.close()

print(f'{dbname} データベースと users テーブルが作成されました。')

データベースの中に、テーブルは複数存在できる。

データベースを作って、
カーソルオブジェクトをつくる。

cur.execute(...): SQL文を実行します。

CREATE TABLE IF NOT EXISTS users: users テーブルを作成します。既に存在する場合は何もしません。
id INTEGER PRIMARY KEY AUTOINCREMENT: id 列を整数型、主キー、自動増加に設定します。
name TEXT NOT NULL: name 列をテキスト型、必須項目に設定します。

age INTEGER: age 列を整数型に設定します。

email TEXT UNIQUE: email 列をテキスト型、一意制約に設定します。

conn.commit(): 変更をデータベースに反映します。

conn.close(): データベース接続を閉じます。

print(...): データベースとテーブルが作成されたことを出力します

0
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?