• sqlite란 2부

    2017. 6. 29. 04:28

    by. 위지원

    connection 객체의 메서드

    1.isolation_level 

    -트랜잭션의 격리 수준을 확인하고 설정

    -none으로 설정하면 자동 커밋모드

    -DEFERRED,IMMEDIATE,EXCULUSIVE 옵션이 있음

    2.cusor

    -커서 객체 생성

    3.commit

    -현재 트랜잭션 커밋

    4.rollback

    -commit을 해버리면 roolback을 할 수 없음

    5.excute,executemany

    -many를 붙이면 한번에 여러개의 쿼리문 실행할 수 있음

    6.create_function(나중에 사용할 함수이름,파라미터,함수이름)

    -사용자 정의 함수를 작성

    import sqlite3
    import md5
    
    def md5sum(t):
        return md5.md5(t).hexdigest()
    
    con = sqlite3.connect(":memory:")
    con.create_function("md5", 1, md5sum)
    cur = con.cursor()
    cur.execute("select md5(?)", ("foo",))
    print cur.fetchone()[0]
    

    7.create_aggregate(나중에 사용할 함수이름,파라미터,클래스 이름)

    -class를 정의해서 사용할 수 있음

    import sqlite3
    
    class MySum:
        def __init__(self):
            self.count = 0
    
        def step(self, value):
            self.count += value
    
        def finalize(self):
            return self.count
    
    con = sqlite3.connect(":memory:")
    con.create_aggregate("mysum", 1, MySum)
    cur = con.cursor()
    cur.execute("create table test(i)")
    cur.execute("insert into test(i) values (1)")
    cur.execute("insert into test(i) values (2)")
    cur.execute("select mysum(i) from test")
    print cur.fetchone()[0]
    

    8. create_collation ..... #이거는 test를 한번 해봐야 이해할 수 있을것 같다 !


    9.interrupt

    모든 쿼리를 중단하고 호출자가 예외를 받음


    ...너무 많고 지금 알필요가 있을까 싶다..

    나머지 모듈은 https://docs.python.org/2/library/sqlite3.html#connection-objects 에서 추가적으로 필요할 때 확인!



    sqlite3를 효율적으로 이용하기!

    1.반복적으로 사용되는 값을 미리 선언해서 사용

    import sqlite3
    
    persons = [
        ("Hugo", "Boss"),
        ("Calvin", "Klein")
        ]
    
    con = sqlite3.connect(":memory:")
    
    # Create the table
    con.execute("create table person(firstname, lastname)")
    
    # Fill the table
    con.executemany("insert into person(firstname, lastname) values (?, ?)", persons)
    
    # Print the table contents
    for row in con.execute("select firstname, lastname from person"):
        print row
    
    print "I just deleted", con.execute("delete from person").rowcount, "rows"
    


    2.index 대신 name으로 cloumns에 접근  ##코딩해볼것 

    -대소문자를 구분하지 않음

    import sqlite3
    
    con = sqlite3.connect(":memory:")
    con.row_factory = sqlite3.Row
    
    cur = con.cursor()
    cur.execute("select 'John' as name, 42 as age")
    for row in cur:
        assert row[0] == row["name"]
        assert row["name"] == row["nAmE"]
        assert row[1] == row["age"]
        assert row[1] == row["AgE"]
    


    3.컨텍스트 관리자로 컨넥션 객체 이용

    import sqlite3
    import sqlite3
    
    con = sqlite3.connect(":memory:")
    con.execute("create table person (id integer primary key, firstname varchar unique)")
    
    # Successful, con.commit() is called automatically afterwards
    with con:
        con.execute("insert into person(firstname) values (?)", ("Joe",))
    
    # con.rollback() is called after the with block finishes with an exception, the
    # exception is still raised and must be caught
    try:
        with con:
            con.execute("insert into person(firstname) values (?)", ("Joe",))
    except sqlite3.IntegrityError:
        print "couldn't add Joe twice"
    


    일반적인 문제 _ 멀티스레딩에 대해..


    이전 sqlite버전에서는 스레드간 connection과 cursor를 공유하지 않기 떄문에 연결공유에 문제가있는데..

    이는 여전하다고 함,, 런타임 에러 발생!


    유일한 exception은 interrupt메서드로  다른 스레드에서 필요한 메서드를 호출하는것..


    The only exception is calling the interrupt() method, 

    which only makes sense to call from a different thread.


    출처url

    https://docs.python.org/2/library/sqlite3.html#connection-objects

    '2017년 > Database' 카테고리의 다른 글

    DB Browser for SQLite  (0) 2017.07.05
    sas university edition을 사용해보자  (0) 2017.06.29
    데이터 베이스 설계 1부  (0) 2017.06.26
    데이터 베이스 개요  (0) 2017.06.26
    sqlite란 1부  (0) 2017.06.25

    대화의 장 💬