0014.1 faker로 더미 데이터 만들기 🐍
간단 사용법
from faker import Faker
fake = Faker()
fake.name()
fake.address()
fake.text()
사용예제 (MySQL에 두 테이블에 쓸 데이터 생성)
import mysql.connector
from faker import Faker
import random
# MySQL 연결 설정
con = mysql.connector.connect(
host="localhost", user="root", password="oz-password", database="testdb"
)
cur = con.cursor()
faker = Faker(["en_US", "ko_KR"])
# users 데이터 생성
for _ in range(100):
username = faker.user_name()
email = faker.email()
cur.execute("INSERT INTO users(username, email) VALUES(%s, %s)", (username, email))
# user_id 불러오기
cur.execute("SELECT user_id FROM users")
fetchall = cur.fetchall()
# print(fetchall)
users = [tup[0] for tup in fetchall]
# orders 데이터 생성
for _ in range(len(fetchall)):
user_id = random.choice(users)
product_name: str = faker.word()
quantity = random.randint(1, 100)
try:
sql = "INSERT INTO orders(user_id, product_name, quantity) VALUES (%s, %s, %s)"
values = (user_id, product_name, quantity)
cur.execute(sql, values)
except:
print("[ERROR] Something BAD happened! 💀")
pass
con.commit()
cur.close()
con.close()
Default Providers