Language/Python

[Python] csv파일 data들 MySQL table에 insert 하기 - pymysql, csv

Ella_K 2022. 9. 26. 03:07

MySQL

create database dictionary default character set utf8mb3
default collate utf8mb3_general_ci; -- 데이터 베이스 생성
 
show databases;
 
use dictionary; -- dictionary 데이터베이스 이용
 
CREATE TABLE naver_wikipedia(  -- 테이블 생성
id BIGINT PRIMARY KEY AUTO_INCREMENT, 
keyword VARCHAR(500), 
contents VARCHAR(4000),
img_url VARCHAR(500),
detail_url VARCHAR(500))
default character set utf8mb3 collate utf8mb3_general_ci;
 
show tables; -- table들 확인
 
select * from naver_wikipedia limit 100; -- naver_wikipedia 테이블 데이터들 100개 까지 보여줌
 
select count(*) from naver_wikipedia; -- 테이블 data 개수 세기

 

pymysql 이용해서 Insert

conn = pymysql.connect(host='localhost', user='user', password='password', db='dictionary', charset='utf8')
curs = conn.cursor()
sql = "insert into naver_wikipedia (keyword, contents, img_url, detail_url) values (%s, %s, %s, %s)"

for path in glob.glob("./end_csv/*.csv"):
    f = open(path, 'r', encoding='utf-8-sig')
    print(path)
    rdr = csv.reader(f)

    next(rdr)
    for line in rdr:
        keyword = (line[0])
        contents = (line[1])
        img_url = (line[2])
        detail_url = (line[3])
        curs.execute(sql,(keyword,contents,img_url,detail_url))
        conn.commit()

    f.close()

conn.close()

 

'Language > Python' 카테고리의 다른 글

[Python] 클래스  (0) 2022.07.14
[Python] requests 라이브러리  (0) 2022.07.10
[Python] 입출력  (0) 2022.06.22
[Python] 내장함수  (0) 2022.06.17
[Python] 기본 문법 - 함수  (0) 2022.06.15