Database초보우낙
28. 테이블 정의서 홈페이지 만들기 본문
여태까지 만들어뒀던 테이블 정의서 결과를 출력하는 파이썬 코드를 수행합니다.
def table_def(table_name):
import cx_Oracle
import pandas as pd
# Connection details
dsn = cx_Oracle.makedsn('192.168.19.3', 8081, 'orcl')
db = cx_Oracle.connect('system', 'oracle_4U', dsn)
cursor = db.cursor()
# Execute SQL query
query = f"""
SELECT A.COLUMN_ID AS NO
, B.COMMENTS AS "논리명"
, A.COLUMN_NAME AS "물리명"
, A.DATA_TYPE AS "자료형태"
, A.DATA_LENGTH AS "길이"
, DECODE(A.NULLABLE, 'N', 'No', 'Y', 'Yes') AS "Null허용"
, A.DATA_DEFAULT AS "기본값"
FROM ALL_TAB_COLUMNS A
LEFT JOIN ALL_COL_COMMENTS B
ON A.OWNER = B.OWNER
AND A.TABLE_NAME = B.TABLE_NAME
AND A.COLUMN_NAME = B.COLUMN_NAME
WHERE A.TABLE_NAME = :tbl_name
ORDER BY A.COLUMN_ID
"""
cursor.execute(query, tbl_name=table_name.upper())
# Fetch data and metadata for column names
rows = cursor.fetchall()
columns = [col[0] for col in cursor.description] # Get column names from description
# Create DataFrame with correct column names
df = pd.DataFrame(rows, columns=columns)
cursor.close() # It's good practice to close cursor and connection
db.close()
return df
table_def('EMP')
스트림잇(streamlit) 파이썬 모듈?
홈페이지를 쉽게 만들 수 있는 파이썬 모듈
데이터관련 교육 카페 | [ 자본가 vs 노동자 시리즈1 ] 데이터 시각화 홈페이지 만들기 첫번째 - Daum 카페
[ 자본가 vs 노동자 시리즈1 ] 데이터 시각화 홈페이지 만들기 첫번째
[ 자본가 vs 노동자 시리즈1 ] 데이터 시각화 홈페이지 만들기 첫번째 내용 한국 경제 신문 1월 14일에 소개된 농업 데이터로 고객 맞춤 데이터 분석 홈페이지 만들어주는 회사 (https://www.farmair.kr/)
cafe.daum.net
파이썬 3.1버전을 설치
https://www.python.org/downloads/release/python-3109/
Python Release Python 3.10.9
The official home of the Python Programming Language
www.python.org
해당링크로 들어가서 아래로 내리면 Files에서 windows installer(64-bit)를 다운로
폴더를 열고
C:\Users\itwill\AppData\Local\Programs\Python\Python310\Scripts
위의 경로로 이동한다 (해당 폴더는 파이썬을 다운받으면 생성된다)
명령 프롬포트 창을 열고 경로로 이동후 install 받아준다
pip는 외부에 있는 파이썬 모듈을 설치하는 명령어이다.
cd C:\Users\itwill\AppData\Local\Programs\Python\Python310\Scripts
pip install streamlit
명령 프롬포트 창에서 뒤로 한칸 이동한다
cd ..
streamlit를 실행한다
python -m streamlit hello
다시 해당 디렉토리로 이동후에 cx_Oracle를 install시켜준다
C:\Users\itwill\AppData\Local\Programs\Python\Python310\Scripts
app2.py 스크립트
(이 스크립트는 쥬피터에서 실행용이 아니다)
import cx_Oracle
import pandas as pd
import streamlit as st
def table_def(table_name):
import cx_Oracle
import pandas as pd
import streamlit as st
# Connection details
dsn = cx_Oracle.makedsn('192.168.19.14', 8081, 'orcl')
db = cx_Oracle.connect('system', 'oracle_4U', dsn)
cursor = db.cursor()
# Execute SQL query
query = f"""
SELECT A.COLUMN_ID AS NO
, B.COMMENTS AS "논리명"
, A.COLUMN_NAME AS "물리명"
, A.DATA_TYPE AS "자료형태"
, A.DATA_LENGTH AS "길이"
, DECODE(A.NULLABLE, 'N', 'No', 'Y', 'Yes') AS "Null허용"
, A.DATA_DEFAULT AS "기본값"
FROM ALL_TAB_COLUMNS A
LEFT JOIN ALL_COL_COMMENTS B
ON A.OWNER = B.OWNER
AND A.TABLE_NAME = B.TABLE_NAME
AND A.COLUMN_NAME = B.COLUMN_NAME
WHERE A.TABLE_NAME = :tbl_name
ORDER BY A.COLUMN_ID
"""
cursor.execute(query, tbl_name=table_name.upper())
# Fetch data and metadata for column names
rows = cursor.fetchall()
columns = [col[0] for col in cursor.description] # Get column names from description
# Create DataFrame with correct column names
df = pd.DataFrame(rows, columns=columns)
cursor.close() # It's good practice to close cursor and connection
db.close()
return df
a =table_def('EMP')
st.dataframe(a) # Same as st.write(df)
해당 스크립트를
C:\Users\itwill\AppData\Local\Programs\Python\Python310
경로로 이동후
새로만들기 -> 테스트파일 -> app2.sy로 만들고 안에 해당 스크립트를 저장해준다
명령 프롬포트창에서 위의 디렉토리로 이동후 app2.py를 실행합니다
python -m streamlit run app2.py
데이터파일을 불러와서 표 형태로 띄어준다.
app2.py 스크립트를 메모장으로 열어서 title을 추가해준다
추가해준 내용이 정의서에 추가되어있다.
이번엔 input을 추가해준다.
input으로 테이블 명을 입력할 수 있게 되었다(아직 emp만 입력가능하다)
![]() |
![]() |
테이블을 입력시 해당 테이블에 대한 테이블 정의서가 출력된다.
없는 테이블을 입력시 입력한 테이블에 대한 정보가 없다고 출력된다.
유저 선택하기!
<테이블 정의서 완성본>
import cx_Oracle
import pandas as pd
import streamlit as st
def fetch_tables(owner): # 유져명을 넣으면 테이블명 리스트가 출력되는 함수
# 오라클 접속 정보 3줄을 기술합니다.
dsn = cx_Oracle.makedsn('192.168.19.14', 8081, 'orcl')
db = cx_Oracle.connect('system', 'oracle_4U', dsn)
cursor = db.cursor()
# 유져명을 넣으면 해당 유져의 테이블 리스트를 출력하는 코드
query = """
SELECT table_name FROM all_tables WHERE owner = :owner ORDER BY table_name
"""
cursor.execute(query, owner=owner.upper())
rows = cursor.fetchall()
cursor.close()
db.close()
# 테이블명을 리스트 변수에 담아서 리턴합니다.
return [row[0] for row in rows]
def table_def(table_name):
import cx_Oracle
import pandas as pd
import streamlit as st
# Connection details
dsn = cx_Oracle.makedsn('192.168.19.14', 8081, 'orcl')
db = cx_Oracle.connect('system', 'oracle_4U', dsn)
cursor = db.cursor()
# Execute SQL query
query = f"""
SELECT A.COLUMN_ID AS NO
, B.COMMENTS AS "논리명"
, A.COLUMN_NAME AS "물리명"
, A.DATA_TYPE AS "자료형태"
, A.DATA_LENGTH AS "길이"
, DECODE(A.NULLABLE, 'N', 'No', 'Y', 'Yes') AS "Null허용"
, A.DATA_DEFAULT AS "기본값"
FROM ALL_TAB_COLUMNS A
LEFT JOIN ALL_COL_COMMENTS B
ON A.OWNER = B.OWNER
AND A.TABLE_NAME = B.TABLE_NAME
AND A.COLUMN_NAME = B.COLUMN_NAME
WHERE A.TABLE_NAME = :tbl_name
ORDER BY A.COLUMN_ID
"""
cursor.execute(query, tbl_name=table_name.upper())
# Fetch data and metadata for column names
rows = cursor.fetchall()
columns = [col[0] for col in cursor.description] # Get column names from description
# Create DataFrame with correct column names
df = pd.DataFrame(rows, columns=columns)
cursor.close() # It's good practice to close cursor and connection
db.close()
return df
st.title('테이블 정의서 조회')
selected_owner=st.selectbox("DB 유져명을 선택하세요:", ['SCOTT','SH','HR','OE'])
table_names = fetch_tables(selected_owner)
selected_table = st.selectbox("테이블을 선택하세요:", table_names)
if selected_table: # selected_table 변수에 값이 있다면 true 입니다.
table_info = table_def(selected_table) # table_def 함수에 테이블명을 넣어서
if not table_info.empty: # 만약에 table_info변수가 비어있지 않다면
st.dataframe(table_info) # 테이블 정의서를 홈페이지에 출력해라
else:
st.write("입력한 테이블에 대한 정보가 없습니다")
'파이썬' 카테고리의 다른 글
28-2. 홈페이지 구현하기 (0) | 2024.04.25 |
---|---|
28. 테이블 정의서 홈페이지 만들기 (0) | 2024.04.25 |
27. DBA의 DB관리 문서 생성을 파이썬으로 쉽게 구현하 (0) | 2024.04.24 |
26. undo tablespace와 temp tablespace의 사용량만 집중적으로 시각화 (0) | 2024.04.22 |
25. LAV128 활용하는 팁 2 (0) | 2024.04.22 |