-
12. DB: database 및 table 다루기공부합시다!/python 2023. 2. 6. 00:11728x90
오늘은 Python을 이용한 DB 관리에 대해서 알아보겠습니다.
Python에는 기본적으로 sqlite라는 작은 DB가 내장되어 있습니다.
sqlite를 활용해서 DB생성 및 Table를 생성하고 삭제하는 방법에 대해서 살펴보겠습니다.
''' 데이터베이스 및 테이블 생성 1. SQLite 기본 사용법 2. 테이블 생성 3. 데이터 삽입 4. 기본 SQL 사용 예제 ''' # Python + Database 연동(SQLite) # 테이블 생성 및 삽입 import sqlite3 import datetime # 버전 확인 print('SQListe.version : ', sqlite3.version) print('SQListe.sqlite_version : ', sqlite3.sqlite_version) # 삽입 날짜 생성 now = datetime.datetime.now() print('now : ', now) nowDatetime = now.strftime('%Y-%m-%d %H:%M:%S') print('nowDatetime: ', nowDatetime) # DB생성 & Auto commit(Rollback) conn = sqlite3.connect('./resource/database.db', isolation_level=None) #Cusor c = conn.cursor() print('Cusor Type : ', type(c)) # 테이블 생성(Data Type: TEXT, NUMERIC, INTEGER, REAL, BLOB) c.execute("create table if not exists users(id integer primary key, username text, \ email text, phone text, website text, regdate text)") # 데이터 삽입 #c.execute("insert into users values(1, 'Kim', 'Kim@naver.com', '010-1111-1111', 'Kim.com', ?)", (nowDatetime)) #c.execute("insert into users(id, username, email, phone, website, regdate) values(?,?,?,?,?,?)", \ #(2, 'Park', 'Park@daum.net', '010-2222-2222', 'Park.com', nowDatetime)) # Many 삽입(튜플, 리스트) userList = ( (1, 'Kim', 'Kim@naver.com', '010-1111-1111', 'Kim.com', nowDatetime), (2, 'Park', 'Park@daum.net', '010-2222-2222', 'Park.com', nowDatetime), (3, 'Lee', 'Lee@gmail.com', '010-3333-3333', 'Lee.com', nowDatetime), (4, 'Cho', 'Cho@daum.net', '010-4444-4444', 'Cho.com', nowDatetime), (5, 'Yoo', 'Yoo@google.com', '010-5555-5555', 'Yoo.com', nowDatetime) ) c.executemany("insert into users(id, username, email, phone, website, regdate) \ values (?,?,?,?,?,?)", userList) # Table 삭제 #conn.execute("delete from users") #print('users db deleted : ', conn.execute("delete from users").rowcount) # 커밋: isolation_level = None 일 경우 자동 반영(오토 커밋) # conn.commit() # 롤백 # conn.rollback() # 접속해제 #conn.close()
728x90'공부합시다! > python' 카테고리의 다른 글
13. DB: DB data 다루기 - 2 (0) 2023.02.08 13. DB: DB data 다루기 - 1 (0) 2023.02.07 11.Function (0) 2023.02.03 10.for, while: 흐름제어 (0) 2023.02.02 9.if 조건문: 흐름제어 (0) 2023.02.01