[Windows에서 MySQL 사용법]
Docker 설치 후, mysql를 pull하여 image 다운 후 실행
> docker run --name mysql_test -e MYSQL_ROOT_PASSWORD=1234 -d
-p 3306:3306 mysql:latest
> docker exec -it ee18155087ae /bin/bash
# mysql -u root -p
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)
: 에러 메세지 나옴
> docker ps -a
ee18155087ae mysql:latest "docker-entrypoint.s…" 5 minutes ago Exited (0) 7 seconds ago mysql-container
598d87a1bddc mysql "docker-entrypoint.s…" 8 days ago Exited (255) 41 hours ago 0.0.0.0:3306->3306/tcp, 33060/tcp mysql_test
....
이미 실행된 후 정지된 container있음(port 3306번을 이미 물고 있어서 오류가 남).
실행 중인 container 모두 정지 후, 기존 container 제거.
> docker stop ee18155087ae # 실행 중인 container들 정지
> docker rm -f 598d87a1bddc # 기존 container 제거
> docker restart ee18155087ae # 재시작
...
# mysql -u root -p
비번 1234 넣으니 정상 실행 되며, mysql> prompt로 들어감
db생성하고, 생성된 db 선택 후, table 생성. data를 몇 개 삽입.
mysql> create database opentutorials; # db생성
mysql> drop database opentutorials; # db제거
mysql> show databases; # db보기
mysql> use opentutorials; # db선택
mysql> create table topic( # ";" 안 넣으면 ->로 넘어감
-> id int(11) not null auto_increment,
-> title varchar(100) not null,
-> description text null,
-> created datetime not null,
-> author varchar(30 null,
-> profile varchar(100) null,
-> primary key(id));
mysql> show tables; # 생성 table 확인
mysql> desc topic; # 입력 속성 확인(description)
mysql> insert into topic (title,description,created,author,profile)
values('mysql','mysql is ...',NOW(),'kdj','developer');
mysql> select * from topic; # 삽입된 데이터 확인
mysql> insert into topic (title,description,created,author,profile)
values('oracle','oracle is ...',NOW(),'egoing','developer');
mysql> select * from topic;
mysql> insert into topic (title,description,created,author,profile)
values('postgresql','postgresql is ...',NOW(),'egoing','data scientist, developer');
mysql> insert into topic (title,description,created,author,profile)
values('mongdb','mongodb is ...',NOW(),'egoing','developer');
일부 data만 선택하여 확인해 보기
mysql> select id,title,created,author from topic; # 일부 속성만 선택해 data확인
# author지정 data 선택 / 순서까지 지정 / 건수도 지정
mysql> select id,title,created,author from topic where author='egoing';
mysql> select id,title,created,author from topic where author='egoing' order by id desc;
mysql> select id,title,created,author from topic where author='egoing'
order by id desc limit 2;
mysql>
[python 연동]
> pip install mysql-connector-python
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="1234",
database="opentutorials"
)
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM topic")
myresult = mycursor.fetchall()
for x in myresult:
print(x)
mycursor.execute("insert into topic (title,description,created,author,profile)
values('sqlserver','sqlserver is ...',NOW(),'kaka','database administrator')");
# 데이터베이스 변경 내용 저장
mydb.commit()
출력물:
(1, 'mysql', 'mysql is ...', datetime.datetime(2023, 5, 10, 2, 39, 5), 'kdj', 'developer')
(2, 'oracle', 'oracle is ...', datetime.datetime(2023, 5, 10, 2, 41, 9), 'egoing', 'developer')
(3, 'postgresql', 'postgresql is ...', datetime.datetime(2023, 5, 10, 2, 43, 5), 'hahaha', 'data scientist, developer')
(4, 'mongdb', 'mongodb is ...', datetime.datetime(2023, 5, 10, 2, 43, 46), 'kaka', 'developer')
(5, 'sqlserver', 'sqlserver is ...', datetime.datetime(2023, 5, 10, 5, 16, 31), 'kaka', 'database administrator')
[References]
1. https://opentutorials.org/course/3161
# [참고] https://rondeveloper.tistory.com/m/92
답글삭제docker volume ls
docker volume create testdb-volume
docker volume inspect testdb-volume
docker volume rm testdb-volume
# 명시적 volume 연결
docker run --rm -d --name mysql_test -e MYSQL_ROOT_PASSWORD=1234 -p 3306:3306 -v testdb-volume:/var/lib/mysql mysql:latest #rm옵션: docker stop mysql_test하면 container가 제거됨
docker exec -it mysql_test /bin/bash
mysql -u root -p # password가 안먹으면, 그냥 enter치고 들어가서 root pw만들어 줘야 함
show databases;
create database poops;
use poops;
create table topic(id int(11) not null auto_increment, filename varchar(100) not null, code text null, created datetime not null, primary key(id));
show tables;
desc topic;
insert into topic (filename, code, created) values ('231017_210934_2344',101010,NOW());
select * from topic;
#외부에서 mysql연결이 가능하게 하기 위한 설정
# [참고] https://93it-serverengineer.co.kr/15
create user 'vislab'@'%' identified with caching_sha2_password by '1234';
grant all privileges on poops.* to 'vislab'@'%';
grant grant option on poops.* to 'vislab'@'%';
flush privileges;
docker stop mysql_test # 시간이 좀 걸림(container 제거됨)
docker container ls --all
import mysql.connector
답글삭제mydb = mysql.connector.connect(host="localhost", user="vislab", password="1234", database="poops")
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM topic")
myresult = mycursor.fetchall()
for x in myresult:
print(x)
filename="231019_102345_3434"
code = 1010201
sql = "insert into topic (filename,code,created) values (%s,%s, NOW())"
val = (filename, code)
mycursor.execute(sql, val)
mydb.commit()
#mycursor.execute("insert into topic (filename,code,created) values('231017_180345_7343',1010101,NOW())");
import sqlite3
답글삭제con = sqlite3.connect('db_test3.db')
cur = con.cursor()
cur.execute('''CREATE TABLE poops(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, filename varchar(100) not null, user txt null, email text null, location text null, questions text null, comment text null, created TIMESTAMP DEFAULT CURRENT_TIMESTAMP not null)''')
cur.execute("INSERT INTO poops (filename, user, email, location, questions, comment) VALUES ('231022_094523_2323', 'mymy', 'funmv2023@gmail.com', 'Busan haeundae', 'YNYYNN', 'Normal~~')")
cur.execute("SELECT * FROM poops")
myresult = cur.fetchall()
for x in myresult:
print(x)
con.close()
{"filename":"231022_094523_2323", "user":"hehehe", "email":"aaa@aaa.com", "location":"BusanBusan", "questions":"YNNNY", "comment":"HAHAHA~~~"}
삭제cur.execute('''CREATE TABLE poops(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, filename varchar(100) not null, user txt null, email text null, on_time text null, age integer null, gender text null, location text null, questions text null, comment text null, opt1 text null, opt2 text null, opt3 text null, created TIMESTAMP DEFAULT CURRENT_TIMESTAMP not null)''')
삭제