728x90
반응형
1. OS 사용하기
2. 2. sqlite : 파이썬 내부의 DB(데이터베이스)
3. mariadb 설정
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 17 09:16:58 2022
@author: p011v
"""
'''
클래스에서 사용되는 함수들
__repr__, __init__, __add__ ...
추상함수 : 반드시 오버라이딩 하도록 강제화된 함수 raise NotImplementedError
모듈 : import 모듈명
if__name__=='__main__' : 실제실행되는 경우만 호출
import 모듈명 as 별명
from 모듈명 import 함수명 => 모듈명을 생략됨
정규식 : 문자열의 형태를 지정할 수 있는 방법
import re
파일 : open(파일명, 모드, [encoding])
'''
########## 1. os 사용하기
# 현재 작업 폴더 위치
import os
print(os.getcwd())
# 현재 작업 폴더 변경
os.chdir("C:\KIC\python\workspace")
# 파일 정보 조회하기
import os.path
file="C:\KIC\python\workspace/data.txt" #절대경로
if os.path.isfile(file) :
print(file, "은 파일입니다.")
elif os.path.isdir(file) :
print(file, "은 폴더입니다.")
elif os.path.exists(file) :
print(file, "은 존재합니다.")
else :
print(file, "은 없습니다.")
# 폴더의 하위파일 목록 출력하기
print(os.listdir())
# 문제 : 작업 폴더의 하위 파일목록을 출력하기
# 파일인 경우 : 파일의 크기. os.path.getsize(파일명)
# 폴더인 경우 : 하위 파일의 갯수
import os.path
os.chdir("C:\KIC\python\workspace") # 작업 폴더 설정
cwd = os.getcwd() #작업폴더의 이름
#os.listdir() : 현재폴더의 하위파일(폴더)목록
for f in os.listdir() :
if os.path.isfile(f) :
print(f, " : 파일, 크기 : ", os.path.getsize(f), " 입니다.")
elif os.path.isdir(f) :
os.chdir(f) #작업폴더의 위치를 수정. 상대경로로 작업폴더 설정
print(f, " : 폴더, 하위파일갯수 : ", len(os.listdir())," 개 입니다.")
os.chdir(cwd)
elif os.path.exists(file) :
print(file, "은 존재합니다.")
else :
print(file, "은 없습니다.")
#폴더생성
os.mkdir("temp") #temp 폴더 생성
os.mkdir("data") #data 폴더 생성
#폴더제거
os.rmdir("temp") #temp 폴더 제거
#엑셀파일 읽기
# pip install 실행모듈명 => 모듈을 설정
# openpyxl : xlsx 확장자를 가진 엑셀파일을 읽기/쓰기 위한 모듈
# xlrd : xls 확장자를 가진 엑셀파일을 읽기 위한 모듈
import openpyxl #외부모듈사용. pip install openpyxl
#작업폴더 현재 파이썬 파일(20220617.py)이 있는 폴더
filename = "data/sales_2015.xlsx" #상대경로. 작업폴더 이하부분
#book : 엑셀파일 전체.
book = openpyxl.load_workbook(filename)
sheet = book.worksheets[0] #sheet 중 첫번째 sheet
data=[]
for row in sheet.rows : #sheet의 행들
line = []
for l,d in enumerate(row) :
print(row)
#d.value : 데이터 값
line.append(d.value)
print(line)
data.append(line)
print(data)
#xls 형식의 엘셀파일 읽기
#엑셀파일 읽기위한 모듈
import xlrd #pip install xlrd
infile = "data/ssec1804.xls"
workbook = xlrd.open_workbook(infile) #엑셀파일 전체
print("sheet의 갯수", workbook.nsheets)
# sheets() : 엑셀의 sheet 데이터들
for worksheet in workbook.sheets() :
#worksheet : 한개의 sheet 데이터
print("worksheet 이름: ", worksheet.name)
print("행의 수: ", worksheet.nrows)
print("컬럼의 수: ", worksheet.ncols)
#worksheet.nrows : 행의 수
for row_index in range(worksheet.nrows) :
for column_index in range(worksheet.ncols) :
#row_index : 행의 인덱스 값
#column_index : 컬럼의 인덱스 값
#worksheet.cell_value() : 셀의 값. 데이터 값
print(worksheet.cell_value(row_index, column_index), ",", end="")
print()
'''
csv, 엑셀파일 => 표(테이블,그리드)형태의 데이터.
행, 열로 이루어진 데이터.
=> pasdas 모듈을 이용하여 표형태의 데이터 처리.
=> DataFrame 형식으로 처리함.
'''
########## 2. sqlite : 파이썬 내부의 DB(데이터베이스)
import sqlite3
dbpath = "text.sqlite" # dbpath랑 확장자 생략가능
conn = sqlite3.connect(dbpath) #test.sqlite 데이터베이스 파일 생성.
cur = conn.cursor() #sql 구문 실행 할 수 있는 객체
#executescript :sql문장 여러개 실행 기능
"""
#items 테이블이 존재하면 삭제. 존재하지 않으면 실행 안함.
drop table if exists items;
#items 테이블 생성
item_id integer primary key : 숫자형 기본키설정. 값이 필수. 자동증가됨
name text unique : 문자형 데이터. 중복불가
price integer : 숫자형 데이터
create table items (item_id integer primary key, name text unique, price integer);
#item_id 컬럼제외 : 기본키이므로 값이 자동으로 증가되어 등록됨
insert into items (name,price) values ('Apple', 800);
insert into items (name,price) values ('Orange', 500);
insert into items (name,price) values ('Banana', 300);
"""
cur.executescript("""
drop table if exists items;
create table items (item_id integer primary key,
name text unique, price integer);
insert into items (name,price) values ('Apple', 800);
insert into items (name,price) values ('Orange', 500);
insert into items (name,price) values ('Banana', 300);
""")
conn.commit()
cur = conn.cursor() #문장 실행 객체
cur.execute("select * from items") #문자 실행
item_list = cur.fetchall() #조회된 레코드들을 리스트로 리턴
print(item_list) #[(컬럼값,,,),(컬럼값,,,),...]
for id,name,price in item_list :
print(id,name,price)
'''
문제 : mydb sqlite 데이터베이스 생성
mydb에 member 테이블 생성하기
id char(4) primary key, name char(15), email char(20) 인 컬럼을 가진다.
'''
conn = sqlite3.connect("mydb")
cur = conn.cursor()
cur.execute("create table member (id char(4) primary key, name char(15), email char(20))")
# 화면에서 id, 이름, 이메일을 입력받아 db에 등록하기
while True :
d1 = input("사용자ID: ")
if d1 == '' :
break
d2 = input("사용자이름: ")
d3 = input("이메일: ")
#insert into member (id,name,email) values ('test1','test1','test1@aaa.bbb')
sql = "insert into member (id,name,email) values ('"\
+ d1 + "','" + d2 + "','" + d3 + "')"
print(sql)
cur.execute(sql)
conn.commit()
conn.close() #mydb 데이터베이스와 연결 종료
# mydb의 member 테이블의 내용을 출력하기
import sqlite3
conn = sqlite3.connect("mydb") #mydb 데이터베이스와 연결
cur = conn.cursor() #문장 실행 객체
cur.execute("select * from member") #문자 실행
userlist = cur.fetchall() #조회된 레코드들을 리스트로 리턴
for u in userlist :
print(u)
conn.close() #mydb 데이터베이스와 연결 종료
#파라미터를 이용하여 등록하기
# 화면에서 id, 이름, 이메일을 입력받아 db에 등록하기
conn = sqlite3.connect("mydb") #mydb 데이터베이스와 연결
cur = conn.cursor() #문장 실행 객체
while True :
param = []
d1 = input("사용자ID: ")
if d1 == '' :
break
d2 = input("사용자이름: ")
d3 = input("이메일: ")
sql = "insert into member (id,name,email) values (?,?,?)"
param.append(d1) #첫번째 물음표
param.append(d2) #두번째 물음표
param.append(d3) #세번째 물음표
cur.execute(sql,param)
conn.commit()
conn.close() #mydb 데이터베이스와 연결 종료
conn = sqlite3.connect("mydb") #mydb 데이터베이스와 연결
cur = conn.cursor() #문장 실행 객체
cur.execute("select * from member") #문자 실행
while True :
row = cur.fetchone() #레코드 하나씩 조회
if row == None : #조회 레코드가 없는 경우
break
print(row) #튜플로 조회
conn.close() #mydb 데이터베이스와 연결 종료
# 한꺼번에 데이터 추가하기
data=[('test5','테스트5','test5@aaa.bbb'),
('test6','테스트6','test6@aaa.bbb'),
('test7','테스트7','test7@aaa.bbb'),
('test8','테스트8','test8@aaa.bbb')]
conn = sqlite3.connect("mydb") #mydb 데이터베이스와 연결
cur = conn.cursor() #문장 실행 객체
#executemany : 여러개의 데이터를 한번에 추가하기
cur.executemany("insert into member (id,name,email) values(?,?,?)", data)
conn.commit()
conn.close()
#db 내용 수정하기
# id=leemy의 이메일 leemy2@aaa.bbb로 수정하기
conn = sqlite3.connect("mydb") #mydb 데이터베이스와 연결
cur = conn.cursor() #문장 실행 객체
param = []
param.append("leemy3@aaa.bbb")
param.append("leemy")
cur.executemany("update member set email=? where id=?", param)
conn.commit()
conn.close()
#db 내용 삭제하기
# 이름이 이몽룡인 회원 정보를 삭제하기
conn = sqlite3.connect("mydb") #mydb 데이터베이스와 연결
cur = conn.cursor() #문장 실행 객체
param = []
param.append("이몽룡")
cur.execute("delete from member where name=?", param)
conn.commit()
conn.close()
conn = sqlite3.connect("mydb") #mydb 데이터베이스와 연결
cur = conn.cursor() #문장 실행 객체
cur.execute("select * from member")
while True :
row = cur.fetchone() #레코드 하나씩 조회
if row == None : #조회 레코드가 없는 경우
break
print(row) #튜플로 조회
conn.close() #mydb 데이터베이스와 연결 종료
########## 3. mariadb 설정
# mysql db => 무료 dbms
#1. https://mariadb.org 파일 다운받기
# mariadb-10.6.8-winx64.msi => 설치
# root 사용자 비밀번호설정. remoute checkbox, utf-8 한글 => 선택
#2. HeidiSQL : 윈도우 환경에서 SQL 문장실행가능 툴
#3. root 연결하기. 비밀번호 입력
# kic 사용자 생성
#4. HeidiSQL kic 사용자 연결
# 데이터베이스 생성 : kicdb
#5. item.sql의 문장을 쿼리탭에서 실행
# select * from item 문장실행. 결과 확인
728x90
반응형
'study > Python' 카테고리의 다른 글
[Python] 34. Test 답 (0) | 2022.06.17 |
---|---|
[Python] 34. Test (0) | 2022.06.17 |
[Python] 33. Test 답 (0) | 2022.06.16 |
[Python] 33. Test (0) | 2022.06.16 |
[Python] 33. 클래스에서 사용되는 특별한 함수들, 모듈, 정규식, 파일 읽고 쓰기 (0) | 2022.06.16 |