Python/Python기초

Python 34_ Database 3 insert

Codezoy 2020. 1. 7. 17:16


"""
oracle_config.py
Oracle 데이터베이스 서버에 접속(로그인)하기 위해 필요한 정보들을 정의
"""


     # 사용자 이름
     user = 'scott'

     # 비밀번호
     pwd = 'tiger'

     # 데이터베이스 서버 주소: DSN(Data Source Name)
     dsn = 'localhost:1521/orcl'



>>Oracle 데이터베이스 서버에서 select 구문 실행, 결과 확인
현재 프로젝트 디렉토리 상태





>>Insert 구문 실행하기

import cx_Oracle
import lec08_database.oracle_config as cfg

# database server와 연결 설정
with cx_Oracle.connect(cfg.user, cfg.pwd, cfg.dsn) as connection:
     # SQL 문장을 실행하고, 결과를 분석할 수 있는 cursor 객체 생성
     with connection.cursor() as cursor:
          sql_insert = "insert into dept2 values(91, '강의장10', 'Gangnam')"
 
          cursor.execute(sql_insert)
          sql_select = 'select * from dept2'
          cursor.execute(sql_select)
          # DML(Data Manipulation Language) : insert, update, delete
          # 결과를 영구적으로 반영하기 위해서는 commit을 해야 한다.
          connection.commit()
          for row in cursor:
               print(row)



>> 사용자 입력을 받아서 데이터베이스에 insert
with cx_Oracle.connect(cfg.user, cfg.pwd, cfg.dsn) as connection:
     with connection.cursor() as cursor:
          deptno = int(input('부서번호 입력>>'))
          dname = input('부서이름 입력>>')
          loc = input('부서위치 입력>>')

          sql_insert = f"insert into dept2 values({deptno}, '{dname}', '{loc}')"
# 사용자가 입력한 문자열에 따옴표(')나 큰따옴표(")가 포함되어 있는 경우
# SQL 에러가 발생할 수 있으므로 권장되지 않음.
# -> Data Binding 방법을 권장.
          cursor.execute(sql_insert)
          connection.commit()
          sql_query = 'select * from dept2'
          cursor.execute(sql_query)
          for row in cursor:
               print(row)

실행 결과
부서번호 입력>>11
부서이름 입력>>TiWill
부서위치 입력>>GangNam
(10, 'ACCOUNTING', '뉴욕')
(20, 'RESEARCH', 'DALLAS')
(30, 'SALES', 'CHICAGO')
(40, 'OPERATIONS', 'BOSTON')
(50, '오라클', '서울Seoul')
(60, 'SQL', '제주')
(70, 'DDL', 'Busan')
(80, 'DML', '인천')
(90, 'tiwill', 'gangnam')
(91, '강의장10', 'Gangnam')
(15, 'TiWill', 'GangNam')
(99, 'PL/SQL', '강남')
(22, 'restaurant', 'north korea')
(20, 'TiWill', 'GangNam')
(11, 'TiWill', 'GangNam')