기타/자잘한 Tip
Python에서 sqlite3 사용하기
cocoadev
2009. 8. 26. 10:15
python에서 sqlite3를 사용하는 샘플입니다. mysql등 다른 데이터베이스를 사용하는 방법과 동일하며 간단한 스크립트이기 때문에 보시면 쉽게 이해가 되실 것입니다.
스크립트를 실행하면 아래와 같이 출력되는 것을 확인하실 수 있습니다.
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sqlite3
# DB 연결
db = sqlite3.connect("test.db")
cursor = db.cursor()
datas = [(1, "cheetah"), (2, "puma"), (3, "leopard")]
# 테이블 생성
cursor.execute("create table animal (no, name)")
# 데이터 INSERT
cursor.executemany("insert into animal values (?, ?)", datas)
# 최종 INSERT된 rowid 출력
print 'Last rowid: ' + str(cursor.lastrowid)
# Row count 출력
print 'Row count: ' + str(cursor.rowcount)
# 쿼리
cursor.execute("select * from animal")
for row in cursor:
print row[1]
cursor.execute("update animal set name='jaguar' where no=3");
cursor.execute("select * from animal")
print cursor.fetchall()
cursor.execute("select * from animal where no=1")
row = cursor.fetchone()
print 'No 1 is ' + row[1];
# 종료
cursor.close()
db.commit()
db.close()
# -*- coding: utf-8 -*-
import sqlite3
# DB 연결
db = sqlite3.connect("test.db")
cursor = db.cursor()
datas = [(1, "cheetah"), (2, "puma"), (3, "leopard")]
# 테이블 생성
cursor.execute("create table animal (no, name)")
# 데이터 INSERT
cursor.executemany("insert into animal values (?, ?)", datas)
# 최종 INSERT된 rowid 출력
print 'Last rowid: ' + str(cursor.lastrowid)
# Row count 출력
print 'Row count: ' + str(cursor.rowcount)
# 쿼리
cursor.execute("select * from animal")
for row in cursor:
print row[1]
cursor.execute("update animal set name='jaguar' where no=3");
cursor.execute("select * from animal")
print cursor.fetchall()
cursor.execute("select * from animal where no=1")
row = cursor.fetchone()
print 'No 1 is ' + row[1];
# 종료
cursor.close()
db.commit()
db.close()
스크립트를 실행하면 아래와 같이 출력되는 것을 확인하실 수 있습니다.