파이썬에서 DB에 직접 연결이 필요한 경우가 있습니다. 이에, 파이썬을 이용해 MySQL과 MongoDB에 접근하는 방법을 알아봅니다.
1. MySQL
1.1 DB 연결
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import os
import sys
import logging
import pymysql
# DB 정보.
host = "your host!"
port = "your port!"
username = "your username!"
database = "your database name!"
password = "your password!!"
# MySQL DB 연결.
conn = pymysql.connect(host=host, user=username, passwd=password, db=database, port=port, use_unicode=True, charset='utf8')
# Cursor 생성.
cursor = conn.cursor()
# 다양한 query들을 실행할 수 있음.
query = """CREATE DATABASE IF NOT EXISTS test DEFAULT CHARSET='utf8'"""
cursor.execute(query)
query = """USE test"""
cursor.execute(query)
query = """SHOW TABLES"""
cursor.execute(query)
print(cursor.fetchall())
참고
- CHARSET=’utf8’을 디폴트로 해야 한글로 입력된 파일을 올리는데 문제가 생기지 않음.
- cursor를 통해 실행한 query의 결과는
cursor.fetchall()
을 통해서 확인할 수 있음.
1.2 pandas의 to_sql()
.
사용된 데이터는 ‘서울 열린데이터광장’의 서울시 공공와이파이 위치정보 데이터 입니다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import pandas as pd
df = pd.read_csv("wifi/서울시 공공와이파이 위치정보.csv",encoding='euc-kr')
df.head()
from sqlalchemy import create_engine
dialect = "mysql+pymysql://" + username + ":" + password + "@" + host + ":" + str(port) + "/" + database
engine = create_engine(dialect, encoding='utf-8')
df.to_sql(name='wifi', con=engine, if_exists="replace", index=True)
conn = pymysql.connect(host=host, user=username, passwd=password, db=database, port=port, use_unicode=True, charset='utf8')
cursor = conn.cursor()
cursor.execute("SHOW TABLES")
print(cursor.fetchall())
cursor.execute("select * from wifi limit 1")
print(cursor.fetchall())
2. MongoDB
2.1 DB 연결
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
from pymongo import MongoClient
client = MongoClient('localhost', 27017)
# client = MongoClient('mongodb://localhost:27017/')
# database 확인.
client.list_database_names()
# database 접근.
db = client.mydb
# db = client['mydb']
# database 내 collection 확인.
db.list_collection_names()
# collection 접근.
collection = db.zips
# collection = db['zips']
# document 확인.
import pprint
pprint.pprint(collection.find_one())