Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- 수업기록
- 주피터노트북그래프
- 주피터노트북
- 파이썬데이터분석주피터노트북
- SQL수업
- 파이썬수업
- sql따라하기
- sql연습
- sql연습하기
- 주피터노트북데이터분석
- python수업
- 팀플기록
- 파이썬
- python데이터분석
- SQL
- 파이썬차트
- SQLSCOTT
- 파이썬시각화
- 파이썬알고리즘
- 주피터노트북판다스
- Python
- 판다스데이터분석
- python알고리즘
- 판다스그래프
- matplotlib
- 파이썬데이터분석
- 주피터노트북맷플롯립
- 데이터분석시각화
- 맷플롯립
- 파이썬크롤링
Archives
- Today
- Total
IT_developers
Python 개념 및 실습 - 데이터베이스(1) 본문
파이썬은 내장 데이터베이스가 있음.
내장 브라우저를 볼 수 있는 파일 설치
- Sqlite Database Browser Portable 검색
- DB Browser for SQLite - Standard installer for 64-bit Windows 설치
Desktop에 체크.
설치 완료 후 바탕화면에 DB Breowser 확인.
SQLite
- 파이썬에서만 사용하지 않음
- 원래 내장 DB로 사용하는 데이터베이스
- 프로그램 안에 가지고 있는 DB
- 내장 DB (핸드폰에도 들어있음)
- python, spring boot
- 가벼운 DB 사용할 때
- 관계형 데이터베이스
- 파이썬에서 라이브러리 제공 == sqlite3
#라이브러리 끌어올리기
import sqlite3
from datetime import datetime # datetime 날짜를 알고 싶을 때
# 버전확인
print(sqlite3.version) # 2.6.0
print(sqlite3.sqlite_version) # 3.37.2
# 날짜생성
now = datetime.now()
print("now : ", now)
now_date_time = now.strftime("%Y-%m-%d %H:%M:%S") # strf : string format 지정
print("now_date_time : ", now_date_time)

# 내장 DB 만들기
# sql에서 create 한 것과 같음
conn = sqlite3.connect("data/database.db", isolation_level=None)
data 폴더에 database.db 생성 확인

DB Browser for SQLite 실행 - 데이터베이스 열기
data 폴더에 database.db 열기
# 커서 : 데이터베이스 접근 할 수 있는 객체
cursor = conn.cursor()
print(type(cursor)) # <class 'sqlite3.Cursor'>
# 테이블 생성
# IF NOT EXISTS 테이블 한번만 생성
cursor.execute(
"CREATE TABLE IF NOT EXISTS users(id integer primary key, username text, phone text, website text, regdate text)"
)

# insert : 데이터 넣기
# 한개씩 삽입
from datetime import datetime
now = datetime.now()
now_date_time = now.strftime("%Y-%m-%d %H:%M:%S")
cursor.execute(
"INSERT INTO users VALUES(1,'Kim','010-1234-1234','kim.com',?)",
(now_date_time,) # tuple의 형태로 넣기. ? 값에 대해 튜플로 넣어야함.
)
# ? 넣고 값 맞춰서 적기
cursor.execute(
"INSERT INTO users VALUES(?,?,?,?,?)",
(2, "Hong", "010-1234-4567", "hong.com", now_date_time),
)
# 여러개 삽입. list 형태
user_list = (
(3, "Park", "010-4567-1234", "park.com", now_date_time),
(4, "Choi", "010-9876-1234", "choi.com", now_date_time),
(5, "Yoo", "010-3687-1234", "yoo.com", now_date_time),
)
cursor.executemany("INSERT INTO users VALUES(?,?,?,?,?)", user_list)
데이터 삽입 후 - 데이터 보기에서 확인
# 조회
sql = """ select *
from users
"""
cursor.execute(sql)
# fetchone(), fetchmany(), fetchall() :
print("1", cursor.fetchone()) # select 결과로 나온 제일 첫번째 행

print("2", cursor.fetchmany(size=2)) # 리스트 구조로 출력. 개별 행은 tuple.

print("3", cursor.fetchall())
# 앞에 출력된 2개를 제외하고 남은 데이터 모두 출력
# for문 사용 전체 호출
for row in cursor.fetchall():
print("rows ", row)

# order by 내림차순
sql = """ select *
from users order by id desc
"""
cursor.execute(sql)
for row in cursor.fetchall():
print("rows ", row)

# 특정 조회 (3번만 호출)
sql = """ select *
from users where id = ?
"""
# ?는 tuple로 처리
cursor.execute(sql, (3,))
for row in cursor.fetchall(): # fetchone도 가능. 한개만 출력
print("rows ", row)

# % 사용
sql = """ select *
from users where id = %s
"""
param = 4
cursor.execute(sql % param)
for row in cursor.fetchall():
print("rows ", row)

# 딕셔너리 사용
sql = """ select *
from users where id = :id
"""
cursor.execute(sql, {"id": 5})
for row in cursor.fetchall():
print("rows ", row)

# in 사용
sql = """ select *
from users where id in(?,?)
"""
param = (1, 3)
cursor.execute(sql, param)
for row in cursor.fetchall():
print("rows ", row)

'Python' 카테고리의 다른 글
Python 개념 및 실습 - 게임 (0) | 2022.09.14 |
---|---|
Python 개념 및 실습 - 데이터베이스(2) (0) | 2022.09.14 |
Python 개념 및 실습 - 예외 (0) | 2022.09.13 |
Python 개념 및 실습 - 모듈(2) (0) | 2022.09.12 |
Python 개념 및 실습 - 모듈(1) (0) | 2022.09.12 |
Comments