
๐ค Python์ผ๋ก DB์ ๋ฐ์ดํฐ๋ฅผ ์ ๋ ฅํ ๋, ๋ค์ค ํ์ ์ ๋ ฅํ๋ ๊ฒฝ์ฐ๊ฐ ๋ง์ ๊ฒ์ด๋ค. ์ด๋ฅผ ์ด๋ป๊ฒ ์คํํด์ผ ๊ฐ์ฅ ๋น ๋ฅด๊ฒ ์ ๋ ฅํ ์ ์์๊น?
๐ ์ด๋ฌํ ๊ณ ๋ฏผ์ 3๊ฐ์ง ๋ฐฉ๋ฒ์ ์คํํด๋ดค๊ณ , ๊ฐ ๋ฐฉ๋ฒ์ด ์๊ฐ์ด ์ด๋ป๊ฒ ์ฐจ์ด๋๋ ์ง ๊ณต์ ํด๋ณด๊ณ ์ ํ๋ค.
๋จผ์ ์ ๋ ฅํ ๋ฐ์ดํฐ์ DB๋ฅผ ์ฐ๊ฒฐํ์.
- ์ฌ์ฉ๋ ๋ฐ์ดํฐ๋ 10๋ง๊ฐ์ ํ๊ณผ 3๊ฐ์ ์ด์ ๊ฐ์ง Integer ๋ฐ์ดํฐ๋ฅผ ์ฌ์ฉํ ๊ฒ์ด๋ค.
- DB๋ PostgreSQL๋ก ๊ตฌ์ถํ DB๋ฅผ ํ์ฉํ ๊ฒ์ด๋ค.
import time
import psycopg2
N = 100000
data = [(i,i,i) for i in range(N)]
print('data length: ', len(data)) #10๋ง๊ฐ์ ํ
db = psycopg2.connect(host='localhost', dbname='test', user='postgres', password='postgres', port=5432)
cursor = db.cursor()
1. ๋ฐ๋ณต๋ฌธ ํ์ฉ
sql = "INSERT INTO public.inserttest VALUES (%s,%s,%s);"
start_time = time.time()
for row in data:
try:
cursor.execute(sql, row)
except Exception as e:
print("Insert Error: ", e)
db.commit()
print("%s: %.5f secs" % ("Taken Time", time.time() - start_time))

for๋ฌธ์ ํ์ฉํ ๋ฐฉ๋ฒ์ด๋ค. ์๊ฐ์ ๋ชจ๋ ์ ๋ ฅํ๋๋ฐ, ์ฝ 6.59์ด ๊ฑธ๋ฆฐ๋ค.
์ด๋ฅผ SQL ๋ฌธ์ผ๋ก ํ์ด์ฐ์๋ฉด ์๋์ ๊ฐ๋ค.
INSERT INTO public.inserttest VALUES (0,0,0)
INSERT INTO public.inserttest VALUES (1,1,1)
INSERT INTO public.inserttest VALUES (2,2,2)
INSERT INTO public.inserttest VALUES (3,3,3)
INSERT INTO public.inserttest VALUES (4,4,4);
2. Executemany ํจ์ ํ์ฉ
sql = "INSERT INTO public.inserttest VALUES (%s,%s,%s);"
start_time = time.time()
try:
cursor.executemany(sql, data)
except Exception as e:
print("Insert Error: ", e)
db.commit()
print("%s: %.5f secs" % ("Taken Time", time.time() - start_time))

๋ฐ๋ณต๋ฌธ์ ์ ๊ฑฐํ๊ณ , executemany ํจ์๋ฅผ ์ฌ์ฉํด์ ์ข ๋ ์ฝ๋ ๊ฐ๋ ์ฑ์ด ์ฌ๋ผ๊ฐ ๋ชจ์ต๋๋ค. ํ์ง๋ง ์๋ชจ๋๋ ์๊ฐ์ ์ ์๋ฏธํ๊ฒ ๋ค๋ฅด์ง ์์ ๊ฒ์ผ๋ก ๋ณด์ธ๋ค.
๐ค ํ์ง๋ง ์๋ ๋ธ๋ก๊ทธ๋ฅผ ํ์ธํด๋ณด๋ฉด ์ ์๋ฏธํ๊ฒ ์๊ฐ์ด ๋จ์ถ๋ ๊ฒ์ ํ์ธํ ์ ์๋๋ฐ, ํ์์ ๊ฒฝ์ฐ๋ ๊ทธ๋ ์ง ์์๋ค. ๋์ค์ ์ข ๋ ์ดํด๋ณด์์ผํ ๋ฌธ์ ์ด๋ค.
https://blog.actorsfit.com/a?ID=01750-ec0f0ded-771d-4b06-a47f-7adb203e72c2
3. mogrify ํจ์ ์ฌ์ฉ
args_str = ", ".join([cursor.mogrify('(%s,%s,%s)', row).decode('utf-8') for row in data])
sql = "INSERT INTO public.inserttest VALUES {data};".format(data=args_str)
start_time = time.time()
try:
cursor.execute(sql)
except Exception as e:
print("Insert Error: ", e)
db.commit()
print("%s: %.5f secs" % ("Taken Time", time.time() - start_time))

๐ฅ ์๊ฐ์ด ๋ค์ด๋๋ฏนํ๊ฒ ์ค์๋ค! 100,000 ๊ฐ์ ํ ๊ธฐ์ค์ผ๋ก 10๋ฐฐ ๊ฐ๊น์ด ์๊ฐ์ด ์ ์ฝ๋ ์ ์ด๋ค.
๐ค ์ ๊ทธ๋ด๊น? ๊ทธ ์ด์ ๊ฐ ๋ช ์๋์ด ์๋ ๋ฌธ์๋ ์์ง๋ง, ์ถ์ธกํด๋ณด์๋ฉด 3๋ฒ ๋ฐฉ๋ฒ์์๋ INSERT๋ฌธ ํ ๋ฒ์ ๋ชจ๋ ๋ฐ์ดํฐ๊ฐ ์ ๋ ฅ๋์ด ํธ๋์ญ์ ํ์๊ฐ ์ ์๋ฏธํ๊ฒ ์ค์ด๋ ๋ค. ์ด๊ฒ์ด ์๊ฐ์ด ์ค์ด๋ ์ด์ ๊ฐ ์๋๊ฐ ์ถ์ธก๋๋ค.
INSERT INTO public.inserttest VALUES
(0,0,0), (1,1,1), (2,2,2), (3,3,3), (4,4,4);
๊ฒฐ๋ก
Insert ๋ฌธ์์๋ mogrify ํจ์๋ฅผ ์ฌ์ฉํ๋ ๊ฒ์ด ๊ฐ์ฅ ์๋๊ฐ ๋น ๋ฅด๋ค!
| ๋ฐ๋ณต๋ฌธ ์ฌ์ฉ | Executemany ์ฌ์ฉ | mogrify ์ฌ์ฉ | |
| ์์ ์๊ฐ | 6.592 ์ด | 5.925 ์ด | 0.652 ์ด |
'Engineering ๐ป > CS' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
| [DB] Index๋ (feat. B+-Tree) (0) | 2022.02.13 |
|---|---|
| [DB] SQL๊ณผ NoSQL (0) | 2022.02.02 |
| [CS] ๊ฐ์ฒด ์งํฅ ํ๋ก๊ทธ๋๋ฐ (0) | 2022.01.16 |
| [DB] ๋ฐ์ดํฐ๋ฒ ์ด์ค ๊ธฐ์ด (0) | 2022.01.10 |