변수 사용 가능 범위에 따라 전역변수/지역변수로 나뉨.

 

1) 프로그램 전체에서 유효한 전역변수

   ** 전역 변수는 코드 어디서든  read 가능 하다.

   ** 전역변수에 값을 변경 하려면 global 키워드를 사용하여 함수 내부에 선언 이후 사용 가능하다.

 

2) 함수 내부에서만 유효한 지역변수 (함수 실행 중에만 유효)

 

* 아래 정리된 표 참고 할 것

  Global Variable Local Variable
함수 안에서 읽기 가능 가능
함수 안에서 수정 불가(global 키워드 사용 예외) 가능
함수 밖에서 읽기 가능 불가
함수 밖에서 수정 가능 불가

 

 

 

import pymysql

import pandas as pd

 

# db 정보 설정

test_db = pymysql.connect(

    user='root', 

    passwd='*******', 

    host='localhost', 

    port=3306,

    db='hybris', 

    charset='utf8'

)

 

try:

# 커서 설정

    cursor = hybris_db.cursor(pymysql.cursors.DictCursor)

 

    sql = "SELECT * FROM bankaccount"

 

    cursor.execute(sql)

 

    # fetchall()    모든 데이터를 한 번에 가져올 때 사용

    # fetchone()    한 번 호출에 하나의 행만 가져올 때 사용

    # fetchmany(n)  n개만큼의 데이터를 가져올 때 사용

    result = cursor.fetchall()

 

    result = pd.DataFrame(result)

 

    print(result)

  

    cursor.callproc("PROC_SELECT_BANKACCOUNT", {"23291022400007"})

 

    result = cursor.fetchall()

 

    result = pd.DataFrame(result)

 

    print(result)

 

finally:

    cursor.close() 

    hybris_db.close()

'Python > DB' 카테고리의 다른 글

Python Mysql DB 연동  (0) 2021.05.27

1. PyMySQL 패키지 설치

> pip install PyMySQL

 ref) https://pypi.org/project/PyMySQL/

> pip install pandas

** pandas lib : DataFrame 라이브러리

 ref) https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html

 

2. Source 

import pymysql

import pandas as pd

 

# db 정보 설정

test_db = pymysql.connect(

    user='root', 

    passwd='********', 

    host='localhost', 

    port=3306,

    db='hybris', 

    charset='utf8'

)

 

try:

    # 커서 설정

    cursor = test_db.cursor(pymysql.cursors.DictCursor)

 

    sql = "SELECT * FROM bankaccount"

 

    cursor.execute(sql)

 

    # fetchall()    모든 데이터를 한 번에 가져올 때 사용

    # fetchone()    한 번 호출에 하나의 행만 가져올 때 사용

    # fetchmany(n)  n개만큼의 데이터를 가져올 때 사용

    result = cursor.fetchall()

 

    result = pd.DataFrame(result)

 

    print(result)

 

finally:

    cursor.close() 

    test_db.close()

'Python > DB' 카테고리의 다른 글

Python procedure 호출 (mysql)  (1) 2021.05.27

+ Recent posts