🛠️ 문제 요약:

  • INSERT 후 SELECT 하면 잘 보이지만
  • conn.close() 하니까 사라짐
  • MySQL DB 들어가보니 데이터 없음

🛠️원인

트랜잭션(commit) 을 하지 않아서 생기는 문제야. 😅
MySQL에서는 기본적으로 autocommit이 꺼져 있으면, INSERT, UPDATE, DELETE 같은 변경 작업 후에 commit()을 해야 실제로 데이터베이스에 반영돼.

 

conn.commit()  # 이걸 안 해서 그런거야

 

✅ 해결 방법

파이썬 코드에서 꼭 commit()을 호출해야 해. 예제 보여줄게:

 

import mysql.connector

# 1. 연결
conn = mysql.connector.connect(
    host='localhost',
    user='your_username',
    password='your_password',
    database='your_database'
)

cursor = conn.cursor()

# 2. INSERT 실행
cursor.execute("""
    INSERT INTO users (name, email, age) 
    VALUES (%s, %s, %s)
""", ('홍길동', 'hong@example.com', 30))

# 3. COMMIT 하자! 중요!!
conn.commit()

# 4. SELECT 확인
cursor.execute("SELECT * FROM users WHERE email = %s", ('hong@example.com',))
result = cursor.fetchall()
print(result)

# 5. 마무리
cursor.close()
conn.close()

 

⚠️ 참고로

  • autocommit=True 옵션으로 연결하면 매번 commit() 안 해도 돼:
conn = mysql.connector.connect(..., autocommit=True)

 

하지만 실무에서는 명시적으로 commit() 하는 걸 추천해. 실수 줄이거든.

 

+ Recent posts