FlaskとMySQLでToDoアプリを実装しよう
#mysql.server start
mysql -u root -p
↓ パスワード入力しエンター
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 21
Server version: 8.0.23 Homebrew
Copyright (c) 2000, 2021, Oracle and/or its affiliates.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
#もうあるので飛ばす
todo_appというデータベースとtodoというテーブルを作成
mysql> create database todo_app;
Query OK, 1 row affected (0.00 sec)
todo_appデータベースを使用するためにuseコマンド
use todo_app;
↓
↓
Database changed
(Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Database changed)
todoテーブルを作成
mysql> create table todo(
task_id INT(10) primary key NOT NULL AUTO_INCREMENT,
task_content VARCHAR(200) NOT NULL,
done_flag INT(10) DEFAULT 0,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);
↓
↓
Query OK, 0 rows affected, 2 warnings (0.03 sec)
PythonとMySQLでデータベースと接続
テキストエディタにて 「db.py」というタイトルをつけ該当ディレクトリに保存
↓中身
import MySQLdb
def conn_f():
con = MySQLdb.connect(
user="自分の username",
passwd="自分のpassword",
host="localhost",
db="todo_app",
charset="utf8"
)
# cursor = con.cursor() # カーソルの取得
return con
# Debug
if conn_f():
print("接続成功")
else:
print("接続失敗")
mysqlからexitする
mysql> exit
Bye
python db.py
↓
接続成功
『接続成功』と出力されればdb.pyのコードを下記に変更
import MySQLdb
def conn_f():
con = MySQLdb.connect(
user="root",
passwd="password",
host="localhost",
db="todo_app",
charset="utf8"
)
return con
htmlファイルの作成
db.pyと同じフォルダに、templatesフォルダを作成
index.htmlを作成
下記コード↓
<head>
<meta charset="UTF-8">
</head>
<!DOCTYPE html>
<html lang="ja">
<head>
<title>ToDoアプリケーション</title>
<style>
#main {
width: 60%;
border: solid 1px #ccc;
margin: 0 auto;
text-align: center;
}
form , h1, p{
margin: 0 auto;
text-align: center;
}
hr {
width: 50%;
}
</style>
</head>
<body>
<div id="main">
<form method="POST">
<input type="text" name="content" size="35" placeholder="17:00までに牛乳を1本買う"><br>
<input type="submit" value="追加">
</form>
<h1>TODO</h1>
<hr>
<h1>完了したTODO</h1>
</div>
</body>
</html>
- <head>
- <meta charset="UTF-8">
- </head>
⇑
入れないと文字化けする
ブラウザで表示
タスクの追加
main.pyを作成
コード↓
# 1.必要なモジュールの読み込み
from flask import Flask, request,redirect, url_for, Response,render_template
from db import conn_f
from datetime import datetime as dt
date = dt.now().strftime('%Y:%m:%d %H:%I:%S')
# 2. Flaskを使うためのおまじない
app = Flask(__name__)
# 3.taskテーブルから完了していないtaskを取得する関数
def get_all_tasks():
conn = conn_f()
cursor = conn.cursor()
# user_idを使う場合(今回はこのsqlは実行しません)
# sql = 'select task_id,task_content,done_flag,created_at from todo where user_id= {0};'.format(user_id)
sql = 'select task_id,task_content,done_flag,created_at from todo where done_flag = 0;'
cursor.execute(sql)
tasks = cursor.fetchall()
cursor.close()
conn.close()
return tasks
# 4.taskテーブルから完了しているtaskを取得する関数
def get_all_done_tasks():
conn = conn_f()
cursor = conn.cursor()
# user_idを使う場合(今回はこのsqlは実行しません)
# sql = 'select task_id,task_content,done_flag,created_at from todo where user_id= {0};'.format(user_id)
sql = 'select task_id,task_content,done_flag,created_at from todo where done_flag = 1;'
cursor.execute(sql)
tasks = cursor.fetchall()
cursor.close()
conn.close()
return tasks
# 5. /にアクセスした時に実行されるindex関数
@app.route('/', methods=['GET'])
def index():
tasks = get_all_tasks()
done_tasks = get_all_done_tasks()
# index.htmlにはリストを渡す
return render_template('index.html', tasks=list(tasks), done_tasks=list(done_tasks))
# 6. TODO(タスク)の追加処理
@app.route('/', methods=['GET','POST'])
def add():
conn = conn_f()
cursor = conn.cursor()
sql = 'insert into todo(task_content,done_flag,created_at) values("{0}", {1}, "{2}");'.format(
request.form['content'],
0,
date)
cursor.execute(sql)
conn.commit()
# 接続を閉じる
cursor.close()
conn.close()
# index.htmlにはリストを渡す
tasks = get_all_tasks()
done_tasks = get_all_done_tasks()
# index.htmlにはリストを渡す
return render_template('index.html', tasks=list(tasks), done_tasks=list(done_tasks))
if __name__ == '__main__':
app.run( port=8000)
index.htmlを修正
赤枠部分を削除
下記コードを追加
<div id="main">
<form method="POST">
<input type="text" name="content" size="35" placeholder="17:00までに牛乳を1本買う"><br>
<input type="submit" value="追加">
</form>
<h1>TODO</h1>
{% for task in tasks %}
<form method="post" action="/update">
<input type="text" name="content" value="{{ task[1] }}">
<input type="hidden" name="task_id" value="{{ task[0] }}">
<input type="submit" value="更新" class="btn">
</form>
<form method="post" action="done">
<input type="hidden" name="task_id" value="{{ task[0] }}">
<input type="submit" value="完了" class="btn">
</form>
<hr>
{% endfor %}
</div>
python main.py を実行
↓
* Serving Flask app "main" (lazy loading)
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: off
* Running on http://127.0.0.1:8000/ (Press CTRL+C to quit)
127.0.0.1 - - [24/May/2021 19:02:24] "GET / HTTP/1.1" 200 -
ブラウザでhttp://127.0.0.1:8000/にアクセス
↓
TODO(タスク)の追加処理
main.py
return render_template('index.html', tasks=list(tasks), done_tasks=list(done_tasks))
の下に下記を追加
@app.route('/done', methods=['POST'])
def done():
conn = conn_f()
cursor = conn.cursor()
sql = 'UPDATE todo SET done_flag=1 where task_id={0};'.format(
request.form['task_id'])
cursor.execute(sql)
conn.commit()
cursor.close()
conn.close()
# indexにリダイレクト
return redirect(url_for('index'))
index.html
{% endfor %}の下に下記コード追加
<h1>完了したTODO</h1>
{% for task in done_tasks %}
<p>{{ task[1] }}</p>
{% endfor %}
タスクの更新
main.pyにupdateの部分を追加
# indexにリダイレクト return redirect(url_for('index'))の下に
下記コードを追加
@app.route('/update', methods=['POST'])
def update():
conn = conn_f()
cursor = conn.cursor()
sql = 'UPDATE todo SET task_content="{0}" where task_id={1};'.format(
request.form['content'],
request.form['task_id'])
cursor.execute(sql)
conn.commit()
cursor.close()
conn.close()
tasks = get_all_tasks()
done_tasks = get_all_done_tasks()
# index.htmlにはリストを渡す
return render_template('index.html', tasks=list(tasks), done_tasks=list(done_tasks))
ブラウザには完了したTODOが付け加えられていた
(
)
========================
===↓経過過程ありのver=======
MySQL環境構築
◎Homebrewがインストールされているか?
brew --version
↓
Homebrew 3.1.5
Homebrew/homebrew-core (git revision 8cc1224865; last commit 2021-05-10)
Homebrew/homebrew-cask (git revision 75f162f7e6; last commit 2021-05-10)
実行
brew update
brew tap homebrew/versions
brew info mysql
brew install mysql
↓
To restore the stashed changes to /usr/local/Homebrew/Library/Taps/homebrew/homebrew-services, run:
cd /usr/local/Homebrew/Library/Taps/homebrew/homebrew-services && git stash pop
Updated 4 taps (heroku/brew, homebrew/core, homebrew/cask and homebrew/services).
==> New Formulae
(略)
To upgrade to 8.0.25_1, run:
その後、mysql 起動
mysql.server start
↓
Starting MySQL
SUCCESS!
セキュリティ周りの初期設定
mysql_secure_installation
↓
Securing the MySQL server deployment.
===============================================
Enter password for user root:
↓
設定していたパスワード入力
↓
VALIDATE PASSWORD COMPONENT can be used to test passwords
and improve security. It checks the strength of password
and allows the users to set only those passwords which are
secure enough. Would you like to setup VALIDATE PASSWORD component?
Press y|Y for Yes, any other key for No:
↓
yと入力
↓
y
There are three levels of password validation policy:
LOW Length >= 8
MEDIUM Length >= 8, numeric, mixed case, and special characters
STRONG Length >= 8, numeric, mixed case, special characters and dictionary file
Please enter 0 = LOW, 1 = MEDIUM and 2 = STRONG:
↓
2を入力+エンター
Please enter 0 = LOW, 1 = MEDIUM and 2 = STRONG: 2
↓
Using existing password for root.
Estimated strength of the password: 25
↓
yを入力
Change the password for root ? *1/opt/anaconda3/lib/python3.8/site-packages/MySQLdb/__init__.py", line 130, in Connect
return Connection(*args, **kwargs)
File "/Users/*2/opt/anaconda3/lib/python3.8/site-packages/MySQLdb/connections.py", line 185, in __init__
super().__init__(*args, **kwargs2)
MySQLdb._exceptions.OperationalError: (2002, "Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)")
(base) *3@MacBook-Air2020-2 Todoアプリ %
おそらくこのエラー
解決策は書いていなかった
==================================
↓面白そうなサイト
==================================
下記URLで色々試す
vi netstat -nlp
↓
mysql_config --socket
↓
/tmp/mysql.sock
python db.py
↓
Traceback (most recent call last):
File "db.py", line 16, in <module>
if conn_f():
File "db.py", line 4, in conn_f
con = MySQLdb.connect(
File "/Users/*4/opt/anaconda3/lib/python3.8/site-packages/MySQLdb/__init__.py", line 130, in Connect
return Connection(*args, **kwargs)
File "/Users/*5/opt/anaconda3/lib/python3.8/site-packages/MySQLdb/connections.py", line 185, in __init__
super().__init__(*args, **kwargs2)
MySQLdb._exceptions.OperationalError: (1045, "Access denied for user 'root@localhost'@'localhost' (using password: YES)")
(base) *6@MacBook-Air2020-2 Todoアプリ %
これは駄目だった
おそらく user とhostの部分が間違っている_
pip config
↓
ERROR: Need an action (debug, edit, get, list, set, unset) to perform
$ mysql.server restart
の後に$ mysql -u root -p
use todo_app;
MySQLで新しいユーザーを作成して権限を付与する方法 | DigitalOcean
(base) <<user name>>@MacBook-Air2020-2 Todoアプリ % python db.py
⇑
そして成功した!
userのとこを"localhost"にしていたので普通にroot で良かったらしい
SQLのuser一覧表示してひたすら一覧のを当てはめていた^^;
===================================
htmlファイルの作成
db.pyと同じフォルダに、templatesフォルダを作成
index.htmlを作成
下記コード↓
<head>
<meta charset="UTF-8">
</head>
<!DOCTYPE html>
<html lang="ja">
<head>
<title>ToDoアプリケーション</title>
<style>
#main {
width: 60%;
border: solid 1px #ccc;
margin: 0 auto;
text-align: center;
}
form , h1, p{
margin: 0 auto;
text-align: center;
}
hr {
width: 50%;
}
</style>
</head>
<body>
<div id="main">
<form method="POST">
<input type="text" name="content" size="35" placeholder="17:00までに牛乳を1本買う"><br>
<input type="submit" value="追加">
</form>
<h1>TODO</h1>
<hr>
<h1>完了したTODO</h1>
</div>
</body>
</html>
- <head>
- <meta charset="UTF-8">
- </head>
⇑
入れないと文字化けする
ブラウザで表示
タスクの追加
main.pyを作成
コード↓
# 1.必要なモジュールの読み込み
from flask import Flask, request,redirect, url_for, Response,render_template
from db import conn_f
from datetime import datetime as dt
date = dt.now().strftime('%Y:%m:%d %H:%I:%S')
# 2. Flaskを使うためのおまじない
app = Flask(__name__)
# 3.taskテーブルから完了していないtaskを取得する関数
def get_all_tasks():
conn = conn_f()
cursor = conn.cursor()
# user_idを使う場合(今回はこのsqlは実行しません)
# sql = 'select task_id,task_content,done_flag,created_at from todo where user_id= {0};'.format(user_id)
sql = 'select task_id,task_content,done_flag,created_at from todo where done_flag = 0;'
cursor.execute(sql)
tasks = cursor.fetchall()
cursor.close()
conn.close()
return tasks
# 4.taskテーブルから完了しているtaskを取得する関数
def get_all_done_tasks():
conn = conn_f()
cursor = conn.cursor()
# user_idを使う場合(今回はこのsqlは実行しません)
# sql = 'select task_id,task_content,done_flag,created_at from todo where user_id= {0};'.format(user_id)
sql = 'select task_id,task_content,done_flag,created_at from todo where done_flag = 1;'
cursor.execute(sql)
tasks = cursor.fetchall()
cursor.close()
conn.close()
return tasks
# 5. /にアクセスした時に実行されるindex関数
@app.route('/', methods=['GET'])
def index():
tasks = get_all_tasks()
done_tasks = get_all_done_tasks()
# index.htmlにはリストを渡す
return render_template('index.html', tasks=list(tasks), done_tasks=list(done_tasks))
# 6. TODO(タスク)の追加処理
@app.route('/', methods=['GET','POST'])
def add():
conn = conn_f()
cursor = conn.cursor()
sql = 'insert into todo(task_content,done_flag,created_at) values("{0}", {1}, "{2}");'.format(
request.form['content'],
0,
date)
cursor.execute(sql)
conn.commit()
# 接続を閉じる
cursor.close()
conn.close()
# index.htmlにはリストを渡す
tasks = get_all_tasks()
done_tasks = get_all_done_tasks()
# index.htmlにはリストを渡す
return render_template('index.html', tasks=list(tasks), done_tasks=list(done_tasks))
if __name__ == '__main__':
app.run( port=8000)
index.htmlを修正
赤枠部分を削除
下記コードを追加
<div id="main">
<form method="POST">
<input type="text" name="content" size="35" placeholder="17:00までに牛乳を1本買う"><br>
<input type="submit" value="追加">
</form>
<h1>TODO</h1>
{% for task in tasks %}
<form method="post" action="/update">
<input type="text" name="content" value="{{ task[1] }}">
<input type="hidden" name="task_id" value="{{ task[0] }}">
<input type="submit" value="更新" class="btn">
</form>
<form method="post" action="done">
<input type="hidden" name="task_id" value="{{ task[0] }}">
<input type="submit" value="完了" class="btn">
</form>
<hr>
{% endfor %}
</div>
python main.py を実行
↓
* Serving Flask app "main" (lazy loading)
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: off
* Running on http://127.0.0.1:8000/ (Press CTRL+C to quit)
127.0.0.1 - - [24/May/2021 19:02:24] "GET / HTTP/1.1" 200 -
ブラウザでhttp://127.0.0.1:8000/にアクセス
↓
===================================
* Serving Flask app "main" (lazy loading)
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: off
* Running on http://127.0.0.1:8000/ (Press CTRL+C to quit)
↓
[2021-05-24 18:31:15,981] ERROR in app: Exception on / [GET]
Traceback (most recent call last):
File "/Users/●●/opt/anaconda3/lib/python3.8/site-packages/flask/app.py", line 2447, in wsgi_app
response = self.full_dispatch_request()
File "/Users/●●/opt/anaconda3/lib/python3.8/site-packages/flask/app.py", line 1952, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/Users/●●/opt/anaconda3/lib/python3.8/site-packages/flask/app.py", line 1821, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/Users/●●/opt/anaconda3/lib/python3.8/site-packages/flask/_compat.py", line 39, in reraise
raise value
File "/Users/●●/opt/anaconda3/lib/python3.8/site-packages/flask/app.py", line 1950, in full_dispatch_request
rv = self.dispatch_request()
File "/Users/●●/opt/anaconda3/lib/python3.8/site-packages/flask/app.py", line 1936, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "main.py", line 45, in index
return render_template('index.html', tasks=list(tasks), done_tasks=list(done_tasks))
File "/Users/●●/opt/anaconda3/lib/python3.8/site-packages/flask/templating.py", line 138, in render_template
ctx.app.jinja_env.get_or_select_template(template_name_or_list),
File "/Users/●●/opt/anaconda3/lib/python3.8/site-packages/jinja2/environment.py", line 930, in get_or_select_template
return self.get_template(template_name_or_list, parent, globals)
File "/Users/●●/opt/anaconda3/lib/python3.8/site-packages/jinja2/environment.py", line 883, in get_template
return self._load_template(name, self.make_globals(globals))
File "/Users/●●/opt/anaconda3/lib/python3.8/site-packages/jinja2/environment.py", line 857, in _load_template
template = self.loader.load(self, name, globals)
File "/Users/●●/opt/anaconda3/lib/python3.8/site-packages/jinja2/loaders.py", line 127, in load
code = environment.compile(source, name, filename)
File "/Users/●●/opt/anaconda3/lib/python3.8/site-packages/jinja2/environment.py", line 638, in compile
self.handle_exception(source=source_hint)
File "/Users/●●/opt/anaconda3/lib/python3.8/site-packages/jinja2/environment.py", line 832, in handle_exception
reraise(*rewrite_traceback_stack(source=source))
File "/Users/●●/opt/anaconda3/lib/python3.8/site-packages/jinja2/_compat.py", line 28, in reraise
raise value.with_traceback(tb)
File "/Users/●●/△△/Todoアプリ AIacademy/templates/index.html", line 39, in template
<input type="hidden" name="task_id" value="{{ task[0] }}">
jinja2.exceptions.TemplateSyntaxError: Unexpected end of template. Jinja was looking for the following tags: 'endfor' or 'else'. The innermost block that needs to be closed is 'for'.
127.0.0.1 - - [24/May/2021 18:31:16] "GET / HTTP/1.1" 500 -
127.0.0.1 - - [24/May/2021 18:31:16] "GET /apple-touch-icon-precomposed.png HTTP/1.1" 404 -
127.0.0.1 - - [24/May/2021 18:31:16] "GET /apple-touch-icon.png HTTP/1.1" 404 -
127.0.0.1 - - [24/May/2021 18:31:16] "GET /favicon.ico HTTP/1.1" 404 -
アプリケーションのエラー — Flask Documentation (1.1.x)
↓
HTML - HTMLのIf文エラーへの対処|teratail
Pythonの文法とは異なりjinja2
では{% elif ~ %}
の後には{% endif %}
行が必要です。
というコメントをヒントに
Jinja failing to parse conditions correctly. · Issue #29543 · saltstack/salt · GitHub
{% if grains['os'] == 'value1' %} は {% endif %} で終わらせる
{% for instance in ['value2'] %}は
Do stuff here<色々なコードを挟んで>
{% endfor %}で終わらせる
===================================
Pythonをアップデートしよう ( 3.8.4 )-Lv.1からはじめるブログ
pythonのアップデート
- pip をインストールする
curl -kL https://bootstrap.pypa.io/get-pip.py | python
pipでアップデートするときのコマンド pip update - Qiita
パッケージのインストール
$ pip install <package-name>
pip自体のアップデート
$ pip install -U pip
アップデート必要なパッケージのリスト(これは便利)
$ pip list -o
jinjaがエラー出てたので
pip install jinja 実行
↓すさまじいエラーが出たので最後の2行だけ
ERROR: Could not find a version that satisfies the requirement jinja
ERROR: No matching distribution found for jinja
python -m pip install flask だと動く
これをflaskをjinjaにするとやはり同じエラー
python - Could not find a version that satisfies the requirement <package> - Stack Overflow
===================================
TODO(タスク)の追加処理
main.py
return render_template('index.html', tasks=list(tasks), done_tasks=list(done_tasks))
の下に下記を追加
@app.route('/done', methods=['POST'])
def done():
conn = conn_f()
cursor = conn.cursor()
sql = 'UPDATE todo SET done_flag=1 where task_id={0};'.format(
request.form['task_id'])
cursor.execute(sql)
conn.commit()
cursor.close()
conn.close()
# indexにリダイレクト
return redirect(url_for('index'))
index.html
{% endfor %}の下に下記コード追加
<h1>完了したTODO</h1>
{% for task in done_tasks %}
<p>{{ task[1] }}</p>
{% endfor %}
タスクの更新
main.pyにupdateの部分を追加
# indexにリダイレクト return redirect(url_for('index'))の下に
下記コードを追加
@app.route('/update', methods=['POST'])
def update():
conn = conn_f()
cursor = conn.cursor()
sql = 'UPDATE todo SET task_content="{0}" where task_id={1};'.format(
request.form['content'],
request.form['task_id'])
cursor.execute(sql)
conn.commit()
cursor.close()
conn.close()
tasks = get_all_tasks()
done_tasks = get_all_done_tasks()
# index.htmlにはリストを渡す
return render_template('index.html', tasks=list(tasks), done_tasks=list(done_tasks))
ブラウザには完了したTODOが付け加えられていた
(
)
==================================
ユーザー名とパスワードが必要なよう
MySQLでユーザー一覧を確認する「mysql.userテーブル」 | UX MILK
↓下記コマンド実行
mysql> SELECT Host, User FROM mysql.user;
+-----------+------------------+
「::1」はIPv6におけるlocalhostで、「127.0.01」はIPv4におけるlocalhost
4 rows in set (0.00 sec)
暗号化済のパスワードを表示する
mysql> SELECT Host, User, Password FROM user WHERE User = "wordpress ";
↓
ERROR 1146 (42S02): Table 'todo_app.user' doesn't exist
自分ので何回か実行するがエラー 4つともすべて全滅
SHOW TABLES FROM も全滅
ERROR 1146 (42S02) : MySQL でいこう!
mysql> SHOW TABLES FROM database todo_app;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'database todo_app' at line 1
とりあえず紛らわしいので遊びも兼ねてusername 変更
ユーザー名を変更する(RENAME USER文) | MySQLの使い方
rename user kitsune@localhost to ookami@localhost;
↓
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '.infoschema to first' at line 1
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds t
これもなんかエラー
コマンド実行
mysql -u root
↓パスワードさえ入れられない感じに
ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)
こちらで実行
mysql -u root -p
↓
パスワード入力でmysqlにログインできる
忘れがちだがmysqlで実行するときは最後に; か\gをつける
Commands end with ; or \g.
ことごとくエラーが出る
MySQL :: MySQL 5.6 リファレンスマニュアル :: 6.2.7 アクセス拒否エラーの原因
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'mysql' at line 1
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MyS
-> mysql -u root test;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'mysql -u root test
mysql -u root test' at line 1
my sqlにはログインできている パスワードも正常
↓いつかまた見たいHP
https://style.potepan.com/articles/18389.html
mysql -u root - p
↓mysqlにログインできた
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 11
Server version: 8.0.23 Homebrew
Copyright (c) 2000, 2021, Oracle and/or its affiliates.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql> use todo_app;
↓
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Database changed
ユーザーの一覧や設定された権限などユーザーに関する情報を取得する | MySQLの使い方
現在接続しているユーザーを確認する
select user(), current_user();
↓
+----------------+----------------+
| user() | current_user() |
+----------------+----------------+
| root@jioja | root@jioja |
+----------------+----------------+
1 row in set (0.00 sec)
ユーザーに設定されている権限を確認する
SHOW GRANTS FOR root@jioja (user)
↓
+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Grants for root@localhost |
+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, RELOAD, SHUTDOWN, PROCESS, FILE, REFERENCES, INDEX, ALTER, SHOW DATABASES, SUPER, CREATE TEMPORARY TABLES, LOCK TABLES, EXECUTE, REPLICATION SLAVE, REPLICATION CLIENT, CREATE VIEW, SHOW VIEW, CREATE ROUTINE, ALTER ROUTINE, CREATE USER, EVENT, TRIGGER, CREATE TABLESPACE, CREATE ROLE, DROP ROLE ON *.* TO `root`@`jioja ` WITH GRANT OPTION |
| GRANT APPLICATION_PASSWORD_ADMIN,AUDIT_ADMIN,BACKUP_ADMIN,BINLOG_ADMIN,BINLOG_ENCRYPTION_ADMIN,CLONE_ADMIN,CONNECTION_ADMIN,ENCRYPTION_KEY_ADMIN,FLUSH_OPTIMIZER_COSTS,FLUSH_STATUS,FLUSH_TABLES,FLUSH_USER_RESOURCES,GROUP_REPLICATION_ADMIN,INNODB_REDO_LOG_ARCHIVE,INNODB_REDO_LOG_ENABLE,PERSIST_RO_VARIABLES_ADMIN,REPLICATION_APPLIER,REPLICATION_SLAVE_ADMIN,RESOURCE_GROUP_ADMIN,RESOURCE_GROUP_USER,ROLE_ADMIN,SERVICE_CONNECTION_ADMIN,SESSION_VARIABLES_ADMIN,SET_USER_ID,SHOW_ROUTINE,SYSTEM_USER,SYSTEM_VARIABLES_ADMIN,TABLE_ENCRYPTION_ADMIN,XA_RECOVER_ADMIN ON *.* TO `root`@`jioja` WITH GRANT OPTION |
| GRANT PROXY ON ''@'' TO 'root'@'localhost' WITH GRANT OPTION |
+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
3 rows in set (0.00 sec)
==================================
python db.py
↓下記エラーが出たのでURL参考にする
↓
Traceback (most recent call last):
File "db.py", line 1, in <module>
import MySQLdb
ModuleNotFoundError: No module named 'MySQLdb'
PythonでMySQLを操作する方法:MySQLdb | UX MILK
pip install MySQL-Python
↓
Collecting MySQL-Python
Downloading MySQL-python-1.2.5.zip (108 kB)
|████████████████████████████████| 108 kB 186 kB/s
ERROR: Command errored out with exit status 1:
command: /Users/(username)/opt/anaconda3/bin/python -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/nl/s26r7s454bxdx6r88p3kljhc0000gn/T/pip-install-8sssiahf/mysql-python/setup.py'"'"'; __file__='"'"'/private/var/folders/nl/s26r7s454bxdx6r88p3kljhc0000gn/T/pip-install-8sssiahf/mysql-python/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /private/var/folders/nl/s26r7s454bxdx6r88p3kljhc0000gn/T/pip-pip-egg-info-2d5y1wqr
cwd: /private/var/folders/nl/s26r7s454bxdx6r88p3kljhc0000gn/T/pip-install-8sssiahf/mysql-python/
Complete output (7 lines):
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/private/var/folders/nl/s26r7s454bxdx6r88p3kljhc0000gn/T/pip-install-8sssiahf/mysql-python/setup.py", line 13, in <module>
from setup_posix import get_config
File "/private/var/folders/nl/s26r7s454bxdx6r88p3kljhc0000gn/T/pip-install-8sssiahf/mysql-python/setup_posix.py", line 2, in <module>
from ConfigParser import SafeConfigParser
ModuleNotFoundError: No module named 'ConfigParser'
----------------------------------------
ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.
============================================
pip - Pipインストールでエラー: “python setup.py egg_info” failed with error code 1 - スタック・オーバーフロー
pip install - -upgrade setuptools
↓
Usage:
pip install [options] <requirement specifier> [package-index-options] ...
pip install [options] -r <requirements file> [package-index-options] ...
pip install [options] [-e] <vcs project url> ...
pip install [options] [-e] <local project path> ...
pip install [options] <archive url/path> ...
pip install - -upgrade pip
↓
Usage:
pip install [options] <requirement specifier> [package-index-options] ...
pip install [options] -r <requirements file> [package-index-options] ...
pip install [options] [-e] <vcs project url> ...
pip install [options] [-e] <local project path> ...
pip install [options] <archive url/path> ...
no such option: -u
=====================================
こちらが良さげ
【Python】「Command "python setup.py egg_info" failed with error code 1 in ...」の対処法 - Knowhow,Nohow
pip、setuptoolsが最新ではない
pip install --upgrade pip setuptools
↓
Collecting pip
Downloading pip-21.0.1-py3-none-any.whl (1.5 MB)
|████████████████████████████████| 1.5 MB 498 kB/s
Collecting setuptools
Downloading setuptools-54.1.2-py3-none-any.whl (785 kB)
|████████████████████████████████| 785 kB 73 kB/s
Installing collected packages: pip, setuptools
Attempting uninstall: pip
Found existing installation: pip 20.2.4
Uninstalling pip-20.2.4:
Successfully uninstalled pip-20.2.4
Attempting uninstall: setuptools
Found existing installation: setuptools 50.3.1.post20201107
Uninstalling setuptools-50.3.1.post20201107:
Successfully uninstalled setuptools-50.3.1.post20201107
Successfully installed pip-21.0.1 setuptools-54.1.2
もう一度try 更にエラー文長くなった
pip install MySQL-Python
↓
Collecting MySQL-Python
Using cached MySQL-python-1.2.5.zip (108 kB)
ERROR: Command errored out with exit status 1:
command: /Users/(username)/opt/anaconda3/bin/python -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/nl/s26r7s454bxdx6r88p3kljhc0000gn/T/pip-install-ktaz0k9j/mysql-python_63981195ed56471eaf3a3e2b27d7b4bf/setup.py'"'"'; __file__='"'"'/private/var/folders/nl/s26r7s454bxdx6r88p3kljhc0000gn/T/pip-install-ktaz0k9j/mysql-python_63981195ed56471eaf3a3e2b27d7b4bf/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /private/var/folders/nl/s26r7s454bxdx6r88p3kljhc0000gn/T/pip-pip-egg-info-m0zumxig
cwd: /private/var/folders/nl/s26r7s454bxdx6r88p3kljhc0000gn/T/pip-install-ktaz0k9j/mysql-python_63981195ed56471eaf3a3e2b27d7b4bf/
Complete output (7 lines):
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/private/var/folders/nl/s26r7s454bxdx6r88p3kljhc0000gn/T/pip-install-ktaz0k9j/mysql-python_63981195ed56471eaf3a3e2b27d7b4bf/setup.py", line 13, in <module>
from setup_posix import get_config
File "/private/var/folders/nl/s26r7s454bxdx6r88p3kljhc0000gn/T/pip-install-ktaz0k9j/mysql-python_63981195ed56471eaf3a3e2b27d7b4bf/setup_posix.py", line 2, in <module>
from ConfigParser import SafeConfigParser
ModuleNotFoundError: No module named 'ConfigParser'
----------------------------------------
WARNING: Discarding https://files.pythonhosted.org/packages/a5/e9/51b544da85a36a68debe7a7091f068d802fc515a3a202652828c73453cad/MySQL-python-1.2.5.zip#sha256=811040b647e5d5686f84db415efd697e6250008b112b6909ba77ac059e140c74 (from https://pypi.org/simple/mysql-python/). Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.
Downloading MySQL-python-1.2.4.zip (113 kB)
|████████████████████████████████| 113 kB 751 kB/s
ERROR: Command errored out with exit status 1:
command: /Users/(username)/opt/anaconda3/bin/python -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/nl/s26r7s454bxdx6r88p3kljhc0000gn/T/pip-install-ktaz0k9j/mysql-python_07757f14e04f4c24bcfef8dd525ff809/setup.py'"'"'; __file__='"'"'/private/var/folders/nl/s26r7s454bxdx6r88p3kljhc0000gn/T/pip-install-ktaz0k9j/mysql-python_07757f14e04f4c24bcfef8dd525ff809/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /private/var/folders/nl/s26r7s454bxdx6r88p3kljhc0000gn/T/pip-pip-egg-info-hc626mr4
cwd: /private/var/folders/nl/s26r7s454bxdx6r88p3kljhc0000gn/T/pip-install-ktaz0k9j/mysql-python_07757f14e04f4c24bcfef8dd525ff809/
Complete output (31 lines):
Downloading http://pypi.python.org/packages/source/d/distribute/distribute-0.6.28.tar.gz
Traceback (most recent call last):
File "/private/var/folders/nl/s26r7s454bxdx6r88p3kljhc0000gn/T/pip-install-ktaz0k9j/mysql-python_07757f14e04f4c24bcfef8dd525ff809/distribute_setup.py", line 143, in use_setuptools
raise ImportError
ImportError
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/private/var/folders/nl/s26r7s454bxdx6r88p3kljhc0000gn/T/pip-install-ktaz0k9j/mysql-python_07757f14e04f4c24bcfef8dd525ff809/setup.py", line 7, in <module>
use_setuptools()
File "/private/var/folders/nl/s26r7s454bxdx6r88p3kljhc0000gn/T/pip-install-ktaz0k9j/mysql-python_07757f14e04f4c24bcfef8dd525ff809/distribute_setup.py", line 145, in use_setuptools
return _do_download(version, download_base, to_dir, download_delay)
File "/private/var/folders/nl/s26r7s454bxdx6r88p3kljhc0000gn/T/pip-install-ktaz0k9j/mysql-python_07757f14e04f4c24bcfef8dd525ff809/distribute_setup.py", line 123, in _do_download
tarball = download_setuptools(version, download_base,
File "/private/var/folders/nl/s26r7s454bxdx6r88p3kljhc0000gn/T/pip-install-ktaz0k9j/mysql-python_07757f14e04f4c24bcfef8dd525ff809/distribute_setup.py", line 194, in download_setuptools
src = urlopen(url)
File "/Users/(username)/opt/anaconda3/lib/python3.8/urllib/request.py", line 222, in urlopen
return opener.open(url, data, timeout)
File "/Users/(username)/opt/anaconda3/lib/python3.8/urllib/request.py", line 531, in open
response = meth(req, response)
File "/Users/(username)/opt/anaconda3/lib/python3.8/urllib/request.py", line 640, in http_response
response = self.parent.error(
File "/Users/(username)/opt/anaconda3/lib/python3.8/urllib/request.py", line 569, in error
return self._call_chain(*args)
File "/Users/(username)/opt/anaconda3/lib/python3.8/urllib/request.py", line 502, in _call_chain
result = func(*args)
File "/Users/(username)/opt/anaconda3/lib/python3.8/urllib/request.py", line 649, in http_error_default
raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 403: SSL is required
----------------------------------------
WARNING: Discarding https://files.pythonhosted.org/packages/90/5a/ce7bef80825c2188cf507baf57b37516e18dffdb198a6766a597f703059a/MySQL-python-1.2.4.zip#sha256=e405f9d6be33923d428acaa4db4f4470427f1d15ea0d2d82a933449ace26bbd9 (from https://pypi.org/simple/mysql-python/). Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.
Downloading MySQL-python-1.2.3.tar.gz (70 kB)
|████████████████████████████████| 70 kB 546 kB/s
ERROR: Command errored out with exit status 1:
command: /Users/(username)/opt/anaconda3/bin/python -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/nl/s26r7s454bxdx6r88p3kljhc0000gn/T/pip-install-ktaz0k9j/mysql-python_209f4c0784f44e51abbf568ad50542d9/setup.py'"'"'; __file__='"'"'/private/var/folders/nl/s26r7s454bxdx6r88p3kljhc0000gn/T/pip-install-ktaz0k9j/mysql-python_209f4c0784f44e51abbf568ad50542d9/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /private/var/folders/nl/s26r7s454bxdx6r88p3kljhc0000gn/T/pip-pip-egg-info-6s31mep7
cwd: /private/var/folders/nl/s26r7s454bxdx6r88p3kljhc0000gn/T/pip-install-ktaz0k9j/mysql-python_209f4c0784f44e51abbf568ad50542d9/
Complete output (8 lines):
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/private/var/folders/nl/s26r7s454bxdx6r88p3kljhc0000gn/T/pip-install-ktaz0k9j/mysql-python_209f4c0784f44e51abbf568ad50542d9/setup.py", line 11, in <module>
from setup_posix import get_config
File "/private/var/folders/nl/s26r7s454bxdx6r88p3kljhc0000gn/T/pip-install-ktaz0k9j/mysql-python_209f4c0784f44e51abbf568ad50542d9/setup_posix.py", line 101
print """You shouldn't be running this directly; it is used by setup.py."""
^
SyntaxError: Missing parentheses in call to 'print'. Did you mean print("""You shouldn't be running this directly)?
----------------------------------------
WARNING: Discarding https://files.pythonhosted.org/packages/9a/81/924d6799494cf7fb24370335c2f782088d6ac4f79e4137d4df94cea3582c/MySQL-python-1.2.3.tar.gz#sha256=7de66fbbf923634e7c965aeaefa74642ba75ae20ee1cefcefc3009595b7a7e6e (from https://pypi.org/simple/mysql-python/). Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.
ERROR: Could not find a version that satisfies the requirement MySQL-Python
ERROR: No matching distribution found for MySQL-Python
pip3でmysql-connectorをインストールする方法 - Qiita
sudo pip3 install mysql-connector-python
↓パスワード入力を求められた
↓
WARNING: The directory '/Users/(username)/Library/Caches/pip' or its parent directory is not owned or is not writable by the current user. The cache has been disabled. Check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
Collecting mysql-connector-python
Downloading mysql_connector_python-8.0.23-cp38-cp38-macosx_10_14_x86_64.whl (4.9 MB)
|████████████████████████████████| 4.9 MB 637 kB/s
Requirement already satisfied: protobuf>=3.0.0 in /Users/(username)/opt/anaconda3/lib/python3.8/site-packages (from mysql-connector-python) (3.14.0)
Requirement already satisfied: six>=1.9 in /Users/(username)/opt/anaconda3/lib/python3.8/site-packages (from protobuf>=3.0.0->mysql-connector-python) (1.15.0)
Installing collected packages: mysql-connector-python
Successfully installed mysql-connector-python-8.0.23
↓
WARNING: The directory '/Users/(username)/Library/Caches/pip' or its parent directory is not owned or is not writable by the current user. The cache has been disabled. Check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
Collecting mysql-connector-python-rf
Downloading mysql-connector-python-rf-2.2.2.tar.gz (11.9 MB)
|████████████████████████████████| 11.9 MB 644 kB/s
Building wheels for collected packages: mysql-connector-python-rf
Building wheel for mysql-connector-python-rf (setup.py) ... done
Created wheel for mysql-connector-python-rf: filename=mysql_connector_python_rf-2.2.2-cp38-cp38-macosx_10_9_x86_64.whl size=249462 sha256=d8fc55ec78b1326372931f52376426059d84f2ac4938b7dabb01d7b2ad688073
Stored in directory: /private/tmp/pip-ephem-wheel-cache-xq5gybwo/wheels/f5/66/87/6d9cef740fd440ef390930fdbe6c761dc1efef78ec94a288fd
Successfully built mysql-connector-python-rf
Installing collected packages: mysql-connector-python-rf
Successfully installed mysql-connector-python-rf-2.2.2
Python 3 ImportError: No module named 'ConfigParser' - Stack Overflow
ModuleNotFoundError: No module named 'ConfigParser' ⇢mysqlclient
代わりに使わないといけない?
pip install mysqlclient
↓
Collecting mysqlclient
Downloading mysqlclient-2.0.3.tar.gz (88 kB)
|████████████████████████████████| 88 kB 557 kB/s
Building wheels for collected packages: mysqlclient
Building wheel for mysqlclient (setup.py) ... done
Created wheel for mysqlclient: filename=mysqlclient-2.0.3-cp38-cp38-macosx_10_9_x86_64.whl size=56300 sha256=24d4846b979e3cc86be56ebefe150d8a0b5aec74bce9d1fdc84bc2aa399cd1a7
Stored in directory: /Users/●●/Library/Caches/pip/wheels/3a/c1/c3/5a19639a551c921c2c2b39468f4278ce5aa27b4e386a4158e4
Successfully built mysqlclient
Installing collected packages: mysqlclient
Successfully installed mysqlclient-2.0.3
*1:Press y|Y for Yes, any other key for No) : y
↓
New password:
===============================================
mysql_secure_installation
Securing the MySQL server deployment.
Enter password for user root:
The 'validate_password' component is installed on the server.
The subsequent steps will run with the existing configuration
of the component.
Using existing password for root.
Estimated strength of the password: 25
Change the password for root ? ((Press y|Y for Yes, any other key for No) : s
... skipping.
By default, a MySQL installation has an anonymous user,
allowing anyone to log into MySQL without having to have
a user account created for them. This is intended only for
testing, and to make the installation go a bit smoother.
You should remove them before moving into a production
environment.
ここから先はずっと 「y」選択
Remove anonymous users? (Press y|Y for Yes, any other key for No) : y
Success.
Normally, root should only be allowed to connect from
'localhost'. This ensures that someone cannot guess at
the root password from the network.
Disallow root login remotely? (Press y|Y for Yes, any other key for No) : y
Success.
By default, MySQL comes with a database named 'test' that
anyone can access. This is also intended only for testing,
and should be removed before moving into a production
environment.
Remove test database and access to it? (Press y|Y for Yes, any other key for No) : y
- Dropping test database...
Success.
- Removing privileges on test database...
Success.
Reloading the privilege tables will ensure that all changes
made so far will take effect immediately.
Reload privilege tables now? (Press y|Y for Yes, any other key for No) : y
Success.
All done!
Remove anonymous users? (Press y|Y for Yes, any other key for No) : y
Success.
Normally, root should only be allowed to connect from
'localhost'. This ensures that someone cannot guess at
the root password from the network.
Disallow root login remotely? (Press y|Y for Yes, any other key for No) : y
Success.
By default, MySQL comes with a database named 'test' that
anyone can access. This is also intended only for testing,
and should be removed before moving into a production
environment.
Remove test database and access to it? (Press y|Y for Yes, any other key for No) : y
- Dropping test database...
Success.
- Removing privileges on test database...
Success.
Reloading the privilege tables will ensure that all changes
made so far will take effect immediately.
Reload privilege tables now? (Press y|Y for Yes, any other key for No) : y
Success.
All done!
mysql -u root -p
↓ パスワード入力しエンター
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 21
Server version: 8.0.23 Homebrew
Copyright (c) 2000, 2021, Oracle and/or its affiliates.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
日本語化設定と暗号化プラグインの設定
my.cnfというファイル名で下記コードをテキストエディター作成。
# Default Homebrew MySQL server config
[mysqld]
# Only allow connections from localhost
bind-address = 127.0.0.1
character-set-server=utf8 # この行を追加
default_authentication_plugin=mysql_native_password # この行を追加
下記 mysqlの状態から exitする
↓
mysql> Exit
Bye
サーバーを再起動
mysql.server restart
↓
Shutting down MySQL
. SUCCESS!
Starting MySQL
.. SUCCESS!
サーバーの状態を確認
mysql.server status
↓
SUCCESS! MySQL running (31069)
サーバーをスタート
mysql.server start
↓
Starting MySQL
SUCCESS!
2021-05-24T08:46:05.6NZ mysqld_safe A mysqld process already exists
(もしエラーがでた場合は、一度mysqlをstop
mysql.server stop
↓
Shutting down MySQL
.. SUCCESS!
mysql.server start
↓
Starting MySQL
. SUCCESS!
mysql.server status
↓
SUCCESS! MySQL running (31315) )
FlaskとMySQLでToDoアプリを実装しよう
↓下記コマンドMysqlコンソールを起動・実行
mysql -u root -p
↓
↓パスワード入力
↓
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 10
Server version: 8.0.23 Homebrew
Copyright (c) 2000, 2021, Oracle and/or its affiliates.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
↓
↓my sql シェルが開いた
todo_appというデータベースとtodoというテーブルを作成
mysql> create database todo_app;
Query OK, 1 row affected (0.00 sec)
todo_appデータベースを使用するためにuseコマンド
use todo_app;
↓
↓
Database changed
(Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Database changed)
todoテーブルを作成
mysql> create table todo(
task_id INT(10) primary key NOT NULL AUTO_INCREMENT,
task_content VARCHAR(200) NOT NULL,
done_flag INT(10) DEFAULT 0,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);
↓
↓
Query OK, 0 rows affected, 2 warnings (0.03 sec)
PythonとMySQLでデータベースと接続
テキストエディタにて 「db.py」というタイトルをつけ該当ディレクトリに保存
↓中身
import MySQLdb
def conn_f():
con = MySQLdb.connect(
user="自分の username",
passwd="自分のpassword",
host="localhost",
db="todo_app",
charset="utf8"
)
# cursor = con.cursor() # カーソルの取得
return con
# Debug
if conn_f():
print("接続成功")
else:
print("接続失敗")
mysqlからexitする
mysql> exit
Bye
python db.py
↓
接続成功
『接続成功』と出力されればdb.pyのコードを下記に変更
import MySQLdb
def conn_f():
con = MySQLdb.connect(
user="root",
passwd="password",
host="localhost",
db="todo_app",
charset="utf8"
)
return con
===================================
python db.py 実行
↓
Traceback (most recent call last):
File "db.py", line 15, in <module>
if conn_f():
File "db.py", line 4, in conn_f
con = MySQLdb.connect(
File "/Users/((username
*2:username
*3:username
*4:username)))/opt/anaconda3/lib/python3.8/site-packages/MySQLdb/__init__.py", line 130, in Connect
return Connection(*args, **kwargs)
File "/Users/((username)))/opt/anaconda3/lib/python3.8/site-packages/MySQLdb/connections.py", line 185, in __init__
super().__init__(*args, **kwargs2)
MySQLdb._exceptions.OperationalError: (2005, "Unknown MySQL server host '/tmp/mysql.sock' (0)")
(base) ((username)))@MacBook-Air2020-2 Todoアプリ %
which mysql_config
↓
/usr/local/bin/mysql_config
python db.py
↓
Traceback (most recent call last):
File "db.py", line 18, in <module>
if conn_f():
File "db.py", line 6, in conn_f
conn_f = MySQLdb.connect(
File "/Users/((username
*5:username
*6:username