코딩 라이프/개발환경 셋팅
python sql insert 하기
min0114
2024. 7. 30. 22:50
import pymysql
db_config = { 'host' : '127.0.0.1',
'user': 'root',
'password' : '1234',
'database' : 'test',
'port' : 3306
}
sql_path = r'D:\QT_GUI\Modern_GUI_PyDracula_PySide6_or_PyQt6\sql_test.sql'
connection = pymysql.connect(**db_config)
print(f"connection:{connection}")
try:
with connection.cursor() as cursor:
# SQL 파일 읽기
with open(sql_path, 'r', encoding='utf-8') as file:
sql_queries = file.read()
# 여러 개의 쿼리를 실행할 경우, 쿼리를 세미콜론으로 분리
for query in sql_queries.split(';'):
query = query.strip()
if query:
cursor.execute(query)
# 변경 사항 커밋
connection.commit()
print("SQL 파일이 성공적으로 실행되었습니다.")
data = [ ('Type1', 'Name1', 'Root1', 1),
('Type2', 'Name2', 'Root2', 2),
('Type3', 'Name3', 'Root3', 3)
]
insert_query = '''
INSERT INTO CL (type, name, root, classid)
VALUES (%s, %s, %s, %s);
'''
cursor.executemany(insert_query, data)
# 변경 사항 커밋
connection.commit()
print(f"데이터가 성공적으로 삽입되었습니다.")
finally:
connection.close()
반응형