일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
- jpa
- REACT
- myBatis
- 에러
- spring security 로그인
- 스프링 시큐리티
- Security 로그인
- 리액트 심플캡차
- Spring Boot
- react 상태
- SpringBoot
- error
- react 자동입력방지
- 젠킨스
- 리액트 캡차
- CI
- react 심플캡차
- Spring Security
- 스프링 시큐리티 로그인
- react 캡차
- 스프링
- react simple captcha
- git
- spring error
- build
- 깃
- Docker
- react captcha
- ChatGPT
- maven
- Today
- Total
I can do it(Feat. DEV)
[Python] ChatGPT를 사용한 파이썬 스크립트 작성 본문
📝글을 쓰게 된 계기
신규 프로젝트 진행 중 VO를 만드는데 필드를 하나하나 선언하는 게 너무 비효율적이라 생각되어서
ChatGPT를 사용해 파이썬 스크립트를 작성하여 반복 업무를 줄이고자 함.
1. 환경 세팅
파이썬 스크립트이기 때문에 파이썬은 당연히 설치되어 있어야 함.
그리고 필자는 vsCode를 사용하였음.
혹시 안되어있다면..
🔎 vscode 파이썬 설치: Google 검색
www.google.com
포스팅 보고 파이썬 설치 및 환경변수 설정, vsCode에서 확장까지 진행해야 함.
그리고 psycopg2 라이브러리를 설치해야 함
설치 명령어 : pip install psycopg2
설치되었는지 확인 명령어 : pip show psycopg2
2. 메인 함수 코드 설명
문법이 딱히 어렵지는 않음. ChatGPT를 통해 기본 스크립트문 작성함.
def main():
# 데이터베이스 연결
conn = psycopg2.connect(
dbname='test',
user='user',
password='1234',
host='192.168.10.xx',
port='5432'
)
# 커서 생성
cursor = conn.cursor()
#테이블 명
table_name = 'test_table';
#컬럼명, 컬럼 타입, 컬럼 코멘트 조회 쿼리
cursor.execute(f"""SELECT
a.attname AS column_name,
format_type(a.atttypid, a.atttypmod) AS data_type,
d.description AS column_comment
FROM
pg_catalog.pg_class AS c
JOIN
pg_catalog.pg_attribute AS a ON c.oid = a.attrelid
LEFT JOIN
pg_catalog.pg_description AS d ON (c.oid = d.objoid AND a.attnum = d.objsubid)
WHERE
c.relname = '{table_name}'
AND a.attnum > 0
ORDER BY
a.attnum;""")
columns = cursor.fetchall()
print("columns :::",columns)
# 자바 클래스 생성
java_code = generate_java_class(table_name, columns)
# 생성된 자바 클래스 파일 저장
with open(f"{table_name.upper()}.java", 'w', encoding="utf-8") as file:
file.write(java_code)
# 커넥션 및 커서 닫기
cursor.close()
conn.close()
메인 함수로 db 접속 연결 설정 및 쿼리문으로 필요한 정보를 조회함.
그리고 자바 클래스를 생성하여 로컬에 저장함.
그 후 커넥션 종료.
3. 함수 설명
def generate_java_class(table_name, columns):
# 클래스명 생성
print("table_name :::",table_name)
class_name = table_name.capitalize()
# 필드 생성
fields = []
for column in columns:
field_name = column[0]
field_type = column[1]
field_comment = column[2]
fields.append(f' @Comment(value="{append_comment_field(field_comment)}")\n')
fields.append(f" private {convert_to_java_type(field_type)} {to_camel_case(field_name)};\n")
# 클래스 생성
java_code = f'import lombok.Getter;\nimport org.hibernate.annotations.Comment;\n\n\n@Getter\n'
java_code += f"""public class {class_name.upper()} {{
// 필드
\n{''.join(fields)}
}}
"""
return java_code
테이블 명과 컬럼들을 가져와 자바 코드로 변환해 주는 함수임.
#필드 타입을 java 타입으로 변경하는 함수
def convert_to_java_type(postgres_type):
#현재 String 타입으로만 변경
if 'character varying' in postgres_type:
return 'String'
elif postgres_type == 'integer':
return 'Integer'
elif postgres_type == 'timestamp':
return 'String'
elif postgres_type == 'double precision':
return 'String'
elif postgres_type == 'numeric':
return 'String'
# 추가적인 데이터 타입에 대한 매핑을 여기에 추가할 수 있습니다.
else:
return 'Object' # 기본값으로 Object를 반환합니다.
PostgreSQL 타입을 java 타입에 맞게 변환하는 함수임.
#필드명 카멜케이스로 변경하는 함수
def to_camel_case(column_name):
parts = column_name.split('_')
camel_case_name = parts[0] + ''.join(part.capitalize() for part in parts[1:])
return camel_case_name
필드명을 카멜케이스로 변환하는 함수임.
#코멘트가 없으면 빈 문자열 출력
def append_comment_field(field_comment):
if field_comment is None:
return ""
else:
return field_comment
코멘트를 가져오는데 공백일 때 처리하는 함수임.
📢소스 코드 참고
https://github.com/dedel009/convertScripts
GitHub - dedel009/convertScripts
Contribute to dedel009/convertScripts development by creating an account on GitHub.
github.com
'개발자 모드 > 응용' 카테고리의 다른 글
[GIT] 깃헙 README 3D 잔디 심기 (0) | 2024.07.09 |
---|---|
[Bat] 배치 파일로 간단하게 JDK 버전 전환하기! (2) | 2024.04.04 |
[Mybatis] Pageable로 페이지 처리하기 (2) | 2023.12.27 |
[Spring Data JPA]복합키 설정(PK가 2개 이상일 때) (0) | 2023.11.06 |
[Spring Boot] 디렉토리 변경 후 @Configuration 스캔 이슈 (2) | 2023.11.01 |