프로그래밍/Python

Python 공부 노트 4. - 초간단 RDBMS 프로그래밍

Terry Cho 2013. 1. 14. 23:33

RDBMS 프로그래밍시에는 해당 RDBMS에 대한 드라이버(모듈을) import해야 한다. sqlite의 경우는 이미 들어가 있다. 아래는 가장 기본적인 코드 이다.

import sqlite3


conn = sqlite3.connect("datafile")

cursor = conn.cursor()

cursor.execute("drop table test")

cursor.execute("create table test (name text,count integer)")

cursor.execute("insert into test(name,count) values('Terry',1)")

cursor.execute("insert into test(name,count) values('Cath',2)")

conn.commit()

result = cursor.execute("select * from test")

while True:

    row = result.fetchone()

    if row == None:

        break

    print row[0],row[1]

conn.close()

데이타 베이스 프로그래밍 순서

  1. 먼저 import를 통해서, 해당 데이타베이스를 접근하기 위한 모듈을 import한다.
  2. 해당 모듈.connect를 이용하여 데이타 베이스 connection을 연결한다. dbms에 따라서 connection string이 다르다. sqlite의 경우 파일 기반이기 때문에, 파일경로만 지정하면 되고, mysql의 경우에는 host,userid,userpasswd,dbms 식으로 기술해주면 된다.
  3. 다음은 cursor를 connection으로 부터 생성한다.
  4. cursor.execute를 통해서 query를 실행한다.
  5. select의 경우에는 result를 받은후에
    • - fetchall()의 경우 결과를 모두 리턴
    • - fetchone()의 경우 하나의 row를 리턴
    • - fetchmany(num rows)의 경우 rows의 숫자 만큼 리턴을 한다.
  6. conn.commit을 이용하여 transaction을 commit한다.
  7. 마지막으로 사용한 connection을 close한다.
mysql 데이타베이스도 다르지 않다. (정말 쉽다.)

다음은 약간 더 진보된 코드로, 데이타베이스에 대한 에러 핸들링을 포함하고 있다.

import sqlite3

try:
    conn = sqlite3.connect("datafile")
    cursor = conn.cursor()
    cursor.execute("drop table test")
    cursor.execute("create table test (name text,count integer)")
    cursor.execute("insert into test(name,count) values('Terry',1)")
    cursor.execute("insert into test(name,count) values('Cath',2)")
    conn.commit()
    result = cursor.execute("select * from test")
    while True:
        row = result.fetchone()
        if row == None:
            break
        print row[0],row[1]
except sqlite3.Error, e:
    if conn:
        conn.rollback
finally:
    if conn:
        conn.close()

기본적으로 sqlite 라이브러리가 포함되어 있는게 마음에 든다. 간단한 tutorial이나, 간단한 dbms 프로그래밍의 경우 별도의 라이브러리 설치가 필요없다.




그리드형