LoginSignup
0
0

More than 3 years have passed since last update.

初心者の初心者による初心者のための(Django)Pythonのsqlite3説明

Last updated at Posted at 2020-06-04

*自分の為のメモになります。

sqlite3の導入方法

pythonの場合は、標準でsqlite3が導入されているのかな?自分の場合は、pythonに最初から導入されていました。されていない場合は、導入してください。

外部ファイルを実行する方法

sqlite3のコードの書き方

commands.sql
-- sqlite3をインポートしています
import sqlite3

-- データベースに接続します。データベースがない場合は、新しく作成して、接続します。
-- 作成した場合、同じ階層にdatabase_name.dbのファイルを作成されます。
conn = sqlite3.connect('database_name.db')

-- sqliteを操作するカーソルオブジェクトを作成します。
cur = conn.cursor()

-- テーブルを作成しています。
cur.execute('CREATE TABLE sample_table(id integer, name text, birthday)')

-- #2 テーブルを作成しています。
create table if not exists posts (
 id,
 title,
 body
)

-- table一覧
.tables

-- tableの構造を確認
.shema posts or .shema

-- 動作を閉じています。(必ずこの2つを記述する)
conn.commit()
conn.close()

sqlite3のプログラム実行方法

ターミナルで、上記のコードを動かす場合(外部ファイルを実行する)

1つ目
sqliteを起動してから、実行する方法

$> sqlite3 database_name.db

sqlite> .read commands.sql

2つ目はそのまま実行する方法

$> sqlite3 database_name.db < commands.sql

ターミナルでsqlite3を実行する方法

sqlite3のコマンド集

起動

$> sqlite3 データベース名.db

テーブルを作成する

sqlite> create table posts (title, body)

データベースを削除する場合は

sqlite> rm myapp.db

参照記事
https://qiita.com/saira/items/e08c8849cea6c3b5eb0c

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