drcarter의 DevLog

  • DB API : Python에서 JDBC 같은 역할
  • http://mysql-python.sourceforge.net/ 에서 MySQL 모듈 받음
  • 혹은, sudo apt-get install python-mysql
  • User Guide
  • http://www.devshed.com/c/a/Python/MySQL-Connectivity-With-Python/
  • Python DB API
  • Writing MySQL Scripts with Python DB API
  •  

    1. import MySQLdb
      # DB접속
      db = MySQLdb.connect(db='DB명', user='사용자명', passwd='비밀번호', host='원격서버')

      # 커서생성
      cursor = db.cursor() # 모든 DB 작업은 캐서를 통해서

      # SQL 문 실행 : update 류일 경우에는 영향 받은 레코드 개수
      cursor.execute('''
      SQL 문장
      ''')

      # select
      cursor.execute('select ....')
      cursor.rowcount; # 결과 행수
      cursor.description; # 각 필드 특징 (필드명,데이터형_코드, 표시크기, 내부크기, 정확도, 비율, nullable)

      cursor.fetchone(); # 결과 한개, 더이상 레코드 없으면 None
      curor.fetchmany(); # n 개의 결과. 튜플
      cursor.fetchall(); # 남은 결과 전체. 튜플

      # 튜플이 아닌 사전 형식으로 필드 가져오기
      cursor = db.cursor(MySQLdb.cursors.DictCursor)
      # 위 형태로 커서를 가져오면 fetch*() 메소드 실행 결과가 필드명을 키로 한 사전이다.
    2.  
    3. 커밋/롤백
      db.commit()
    4. db.rollback()

    5. # DB 작업 종료
      cursor.close()
    6. db.close()


    참고로...
    아직 MySQLdb 모듈이 python 버전 2.5까지밖에 지원을 안해주는군요...