[PYTHON] (For myself) Flask_7 (Open database from Flask)

item

  1. Open the database from Flask
    (I'm tired today, so that's it)

1. Open the database from Flask

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()

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

    cursor.close()
    connection.close()

    return render_template('view.html', players = players)

--As for the python side, basically the combination so far --I made it possible to use MySQL in Python with ʻimport pymysql that I did last time. --def getConnection (): return pymysql.connect (), when you call getConnection () , you can get the material to call db. --Enter the information to call in connection with connection = getConnection () --Some of the movements below are the same as last time --And then put the variable assigned toreturn` in Flask's procedure so that it can be used on the html side as well.

view.html


{% for player in players %}
    <p>{{ player }}</p>
{% endfor %}

――A ritual to display the variable passed from the ordinary py side with a for statement ――If you put this in, it's OK for the time being

After that, if you start Flask normally, it will be completed (I will put that of the start below for the time being)

Terminal


$ cd <The name of the folder that contains the working directory>
$ FLASK_APP=<Working py directory name> FLASK_ENV=development flask run

2. At the end

--Quite short ――It seems that you only sleep for 3 hours in 48 hours, so take a break today. ――We will leave it tomorrow (today?) To delete data with SQL or borrow AWS in earnest and move it.

Recommended Posts

(For myself) Flask_7 (Open database from Flask)
(For myself) Flask_6 (Open db from python, Mysql basic (phpMyAdmin))
(For myself) Flask_8 (Add / Edit / Delete in database with python)
(For myself) Flask_5 (Add to txt file)
(For myself) Put Flask in VS Code
(For myself) Flask_3 (form, POST and GET)
python [for myself]
Flask database settings
(For myself) AWS_Flask_3 (Install / Run Flask on AWS)
Introducing WebPay from Flask
Run Django tests for currently open buffers from Emacs
heroku memo (for myself)
Freecad memorandum (for myself)
(For myself) Flask_2 (list and for, extends, and a little more)
From environment construction to deployment for flask + Heroku with Docker
(For myself) Flask_4 (Drop-down menu, view txt data (using table))
Python memo (for myself): Array
Python Tkinter notes (for myself)
Open project trace for engineers
Pipenv usage summary (for myself)
10 Open Source Web Crawlers for 2020
Linux Command Dictionary (for myself)
[Note] [For myself] Django command