MySQL メモ
ユーザ作成+権限付与
bash
sudo mysql -u root -p
※ カラに設定してる
sql
-- CREATE USER sample01@localhost IDENTIFIED BY 'sample01';
-- GRANT CREATE, ALTER, DROP, INSERT, UPDATE, DELETE, SELECT, REFERENCES, RELOAD on *.* TO sample01@% WITH GRANT OPTION;
CREATE USER sample01@'%' IDENTIFIED BY 'sample01'; -- 他の端末からも見る場合
GRANT ALL ON sample01.* TO 'sample01'@'%' WITH GRANT OPTION;
FLUSH PRIVILEGES;
データベース作成
bash
sudo mysql -u sample01 -p
sql
create database sample01;
sql
create table sample01.TEST01 ( field01 varchar(256) );
sql
show databases;
use sample01
show tables;
リモートから接続できるようにする
bash
netstat -ant
# sudo apt install net-tools # netstat なければインストール
bash
tcp 0 0 127.0.0.1:3306 0.0.0.0:* LISTEN
MySQL のデフォルト 3306
で上がってるが、
localhost (127.0.0.1) のみ開いているということ
bash
sudo vim /etc/mysql/mysql.conf.d/mysqld.cnf
# sudo vim /etc/mysql/my.cnf # こっちではなかった
bind-address
をコメントアウトする
conf
#bind-address = 127.0.0.1
#mysqlx-bind-address = 127.0.0.1
設定を反映
bash
sudo systemctl restart mysql
Windows のクライアント
CSE で接続するのはもう無理ぽいので (2024.04時点)、 MySQL 純正の「MySQL Workbench」使うことにする
メモ: もろもろ確認用
sql
show grants for sample01@localhost;
sql
select current_user() from dual;
sql
select Host, User from mysql.user;
Python からアクセスするとき
bash
conda install PyMySQL
py
import pymysql.cursors
conn = pymysql.connect(
host='sugoi-host',
user='sample01',
db='sample01',
password='sample01',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor,
)
try:
with conn.cursor() as cursor:
sql = "insert into TEST01 (FIELD01) values (%s)"
cursor.execute(sql, ('test'))
conn.commit()
finally:
pass
# conn.close()
try:
with conn.cursor() as cursor:
sql = "select * from TEST01"
cursor.execute(sql)
# cursor.execute(sql, ('123',))
result = cursor.fetchall()
print(result)
finally:
pass
# conn.close()
conn.close()