1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

(自分用)Flask_8(pythonでデータベース内の追記/編集/削除)

1
Posted at

項目

  1. データベースの簡単なおさらい
  2. データベース内に追記
  3. データベース内の編集
  4. データベース内の削除

1.簡単なおさらい

python
from flask import Flask, render_template
import pymysql
app = Flask(__name__)

def getConnection():
    return pymysql.connect(
        host='localhost',
        db='mydb',
        user='root',
        password='',
        charset='utf8',
        cursorclass=pymysql.cursors.DictCursor
    )

@app.route('/')
def select_sql():
  
    connection = getConnection()
    message = "Hello world"

    sql = "SELECT * FROM players"
    cursor = connection.cursor()
    cursor.execute(sql)
    players = cursor.fetchall()

    cursor.close()
    connection.close()

    return render_template('view.html', message = message, players = players)
  • pymysqlで編集するよと宣言し
  • .connect()で編集するデータベース情報を選択
  • def select_sqlで選択したデータベースにSQLコマンドを入力

2.データベース内の追記

python
@app.route('/')
def select_sql():
  
    connection = getConnection()
    message = "Hello world"

    cursor = connection.cursor()

    sql = "INSERT INTO players (name, level, job_id) VALUES ('霧島1号', 1, 1)"
    cursor.execute(sql)
    connection.commit()

    sql = "SELECT * FROM players"
    cursor.execute(sql)
    players = cursor.fetchall()

    cursor.close()
    connection.close()

    return render_template('view.html', message = message, players = players)
  • 基本は同じ
  • cursorを参照できる様に、先にcursor = connection.cursor()しといた方がいい
  • sql = "INSERT INTO players (name, level, job_id) VALUES ('霧島1号', 1, 1)"で、INSERT INTO <table名>でtableを選択し、編集したいカラムを選択後、VALUES ('霧島1号', 1, 1)で選択したカラムにデータを追加する。
    カラムと順番と追記データの順番は要連動
  • connection.commit()でデータベースにSQLコマンドを実行?している

3.データベース内の編集

python
    sql = "UPDATE players SET level = 10 WHERE id = 12"
    cursor.execute(sql)
    connection.commit()
  • さっきのINSERTの所をこれで置き換える
  • UPDATE <table名>で編集したいtableを選択SET level=10で選択したlevelカラムの値を10に変更すると選択し指示し、WHERE id = 12でlevelカラムの中のどのデータが編集されるかを選択する

4.データベース内の削除

python
    sql = "DELETE FROM players WHERE id = 12"
    cursor.execute(sql)
    connection.commit()
  • 基本同じ
  • DELETE FROM playersでplayersテーブルから消しますよと宣言し
  • WHERE id = 12「何を?」「idが12の奴を」とやっている

5.終わりに

  • 今日もあんまり出来んかった
  • 一回1日ぐらい休んだ方がいいかもしれない
1
2
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
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?