CoolFace
Apppublic

seriouspark/sql_trainer

sourceHugging Faceapache-2.0updated 3y agoView on Hugging Face
0likes
make_db.py82 linesDownload Raw Back to root
1import streamlit as st2import pandas as pd3import sqlite34import os5from datetime import datetime6 7 8def app():9    st.title('Excel to DataBase')10    st.write('엑셀을 넣어 데이터베이스를 만들어봅시다.')11    file_name = st.text_input('파일명 지정하기')12    # 엑셀 파일 업로드13    uploaded_file = st.file_uploader('Choose an Excel file', type = ['xlsx','xls','csv'])14 15    if uploaded_file is not None:16        # 엑셀 파일을 데이터프레임으로 변환17        try:18            df = pd.read_csv(uploaded_file)19            20        except:21            df = pd.read_excel(uploaded_file)22            23            24        # 각 열에 대한 데이터 타입 선택 옵션 제공25        data_types = {'object': 'String',26                      'float' : 'Float',27                      'int' : 'Integer',28                      'datetime': 'Datetime',29                      'bool' : 'Bool',30                    }31        selected_data_types = {}32        for column in df.columns:33            data_type = st.selectbox(f"SELECT data type for column '{column}'",34                            options = list(data_types.keys()),35                            format_func = lambda x : data_types[x],36                            key = column)37            selected_data_types[column] = data_type38            print(selected_data_types)39        # 원래 int / float 것들 중에서 object 로 변환해야 할 것들은  object 로 바꾸어주기40        if st.button('데이터 변환하고 저장하기'):41            for column, data_type in selected_data_types.items():42                if data_type == 'float':43                    try:44                        df[column] = df[column].str.replace(',','')45                    except:46                        continue47                    df[column] = pd.to_numeric(df[column], errors = 'coerce')48                elif data_type == 'int':49                    try:50                        df[column] = df[column].str.replace(',','')51                    except:52                        continue53                    df[column] = pd.to_numeric(df[column].str.replace(',',''), errors = 'coerce').fillna(0).astype(int)54                elif data_type == 'datetime':55                    df[column] = pd.to_datetime(df[column], errors = 'coerce')56                elif data_type == 'bool':57                    df[column] = df[column].astype(bool)58                elif data_type == 'object':59                    df[column] = df[column].astype(str).str.replace('.0','')60                    61                    62            next = True63        64        65            if next:66                # sql lite 데이터베이스 연결 및 생성67                conn = sqlite3.connect(file_name)68                c = conn.cursor()69                70                # 데이터프레임을 SQL테이블로 변환71                72                df.to_sql(f'{file_name}', conn, if_exists = 'replace', index = False)73                74                st.success(f'파일은 성공적으로 데이터베이스로 저장되었습니다. 데이터베이스명 [{file_name}]')75 76                # 연결 종료77                conn78                conn.close()79 80 81           82