새벽코딩

[Python-DB] 1. 데이터의 입력과 조회 본문

Programming/Python

[Python-DB] 1. 데이터의 입력과 조회

midnightcoder 2022. 12. 22. 16:15

Python 에 내장 모듈인 sqlite3 db를 이용해서 실습을 해봄

 

실습전에, 먼저 c 드라이브 안에 PythonDB 폴더를 만든다.

 

1) 파이썬에서 데이터 입력을 위한 코딩 순서

 

용어

cusor() : DB하고 입력하는 창하고의 통로

 

execute() 안에 query를 작성할 수 있다. (예를 들면, table 생성 및 데이터 삽입 insert into 등..)

 

# 데이터의 입력에 대한 실습
# 파이썬에서 데이터를 입력하는 프로그래밍 순서
# 1. 데이터 베이스에 연결 (연견자 = sqlite3.connect("DB이름")
# 2. 커서 생성 (데이터 입출력 통로, 커서이름 = 연결자.cursor())
# 3. 테이블 만들기 (이미 만들어져 있다면 생략이 가능, 커서이름.execute("create table"))
# 4. 데이터 입력 (커서이름.execute("insert into"))
# 5. 입력한 데이터를 물리적인 공간에 저장 (연결자.commit())
# 6. 데이터베이스(리소스) 닫기(연결자.close())

import sqlite3          #sqlite3 모듈 가져오기
con = sqlite3.connect("c:/PythonDB/naverDB")      #DB 연결
#커서 생성
cur = con.cursor()

cur.execute("drop table if exists userTable")
cur.execute("create table userTable(id char(4), userName char(15),"
            "email char(15), birthYear int)")

# userTable 이 존재하지 않는다면 만들지 않고, 있다면 error 발생 안함
# cur.execute("create table if not exists userTable(id char(4), userName char(15),"
#             "email char(15), birthYear int)")
# 테이블 제대로 만들어졌는지 확인하는 쿼리문
# cur.execute("select * from sqlite_master where type='table';")
# print(cur.fetchall())

# 데이터 4건을 메모리에 올리고 있다.
cur.execute("insert into userTable values('john', 'john Bann', 'john@naver.com', 1990)")
cur.execute("insert into userTable values('kim', 'Kim chi', 'kim@daum.net', 1992)")
cur.execute("insert into userTable values('lee', 'Lee Pal', 'lee@paran.com', 1988)")
cur.execute("insert into userTable values('park', 'Park Su', 'park@gmail.com', 1995)")

#위와 같이 데이터를 insert into 를 통해서 입력했다고하더라도, 메모리(RAM)에 존재하는것이다.
# 그래서 물리적 디스크(서버단) 에 완전히 저장하려면, commit을 해야한다.
con.commit()
con.close()     #DB 연동 해제