본문 바로가기
관/핫한 파이썬 공부

파이썬의 여러 모듈 공부하기 09.

by 4차원 박스 2019. 12. 17.

이번내용은 데이터베이스에 관련한 내용을 알아보며
DBMS를 다뤄볼 예정이다


데이터베이스 시스템은 5가지로 구성된다

1. 데이터 베이스(DB) : 데이터들이 모여있는것
2. 사용자
3. 데이터언어 (sql 이라 한다 = structured query language 의미는 구조화된 질문언어 이다.)
4. 데이터베이스 관리시스템(DBMS = 여러개의 데이터베이스를 가짐)
5. 데이터베이스 기계


내용은 간단히 다음과 같다

데이터베이스에 접근하기 위해서 
데이터언어로 접근하면
데이터베이스 기계에 있는 
데이터베이스 관리시스템이 가지고 있는 데이터베이스에 접근한다.


사용자는 2가지로 나뉜다
1. 일반사용자
2. DBA 데이터베이스 관리자 : 게임에서 방장 혹은 운영자 같은것

대표적인DBMS : my sql, oracle, ms sql, sqlite(가장 간단하게 사용할수 있고 용량부담이 적은 DBMS 이다.) 등등이 있다.

DB의 구조 : 엑셀과 같은 테이블 들로 구성되며 이러한 테이블들은 서로 관계를가진다.


sql 은 3가지로 나뉜다

1. DBA (데이터 조작 언어) : db를 조정하는것 : select, insert, update, delete 등의 4가지 기초문법이 있다
2. DDL (데이터 정의 언어) : db를 만드는것 : creat 가 대표적인 문법
3. DCL (데이터 제어 언어) : db를 제어하는것


sqlite를 다운받는다 sqlite.org에서 자기 운영체제에 맞는 exe를 다운받는다.(참고로 64는 32것도 실행된다.)
cmd창에서 실행이 안되면 
path 통로를 만들어 주어야 어느 디렉토리에 있든 바로 불러서 사용할수 있다.


다음과같이 cmd창에 db를 만들어주자

C:\Users\407-14>sqlite3
SQLite version 3.30.1 2019-10-10 20:19:45
Enter ".help" for usage hints.
Connected to a transient in-memory database.
Use ".open FILENAME" to reopen on a persistent database.
sqlite> create table myDB(name text not null, age int, address char(50));
sqlite> insert into myDB values('park',10,'seoul');
sqlite> insert into myDB values('lee',10,'seoul');
sqlite> .help
.archive ...             Manage SQL archives
.auth ON|OFF             Show authorizer callbacks
.backup ?DB? FILE        Backup DB (default "main") to FILE
.bail on|off             Stop after hitting an error.  Default OFF
.binary on|off           Turn binary output on or off.  Default OFF
.cd DIRECTORY            Change the working directory to DIRECTORY
.changes on|off          Show number of rows changed by SQL
.check GLOB              Fail if output since .testcase does not match
.clone NEWDB             Clone data into NEWDB from the existing database
.databases               List names and files of attached databases
.dbconfig ?op? ?val?     List or change sqlite3_db_config() options
.dbinfo ?DB?             Show status information about the database
.dump ?TABLE? ...        Render all database content as SQL
.echo on|off             Turn command echo on or off
.eqp on|off|full|...     Enable or disable automatic EXPLAIN QUERY PLAN
.excel                   Display the output of next command in spreadsheet
.exit ?CODE?             Exit this program with return-code CODE
.expert                  EXPERIMENTAL. Suggest indexes for queries
.filectrl CMD ...        Run various sqlite3_file_control() operations
.fullschema ?--indent?   Show schema and the content of sqlite_stat tables
.headers on|off          Turn display of headers on or off
.help ?-all? ?PATTERN?   Show help text for PATTERN
.import FILE TABLE       Import data from FILE into TABLE
.imposter INDEX TABLE    Create imposter table TABLE on index INDEX
.indexes ?TABLE?         Show names of indexes
.limit ?LIMIT? ?VAL?     Display or change the value of an SQLITE_LIMIT
.lint OPTIONS            Report potential schema issues.
.load FILE ?ENTRY?       Load an extension library
.log FILE|off            Turn logging on or off.  FILE can be stderr/stdout
.mode MODE ?TABLE?       Set output mode
.nullvalue STRING        Use STRING in place of NULL values
.once (-e|-x|FILE)       Output for the next SQL command only to FILE
.open ?OPTIONS? ?FILE?   Close existing database and reopen FILE
.output ?FILE?           Send output to FILE or stdout if FILE is omitted
.parameter CMD ...       Manage SQL parameter bindings
.print STRING...         Print literal STRING
.progress N              Invoke progress handler after every N opcodes
.prompt MAIN CONTINUE    Replace the standard prompts
.quit                    Exit this program
.read FILE               Read input from FILE
.recover                 Recover as much data as possible from corrupt db.
.restore ?DB? FILE       Restore content of DB (default "main") from FILE
.save FILE               Write in-memory database into FILE
.scanstats on|off        Turn sqlite3_stmt_scanstatus() metrics on or off
.schema ?PATTERN?        Show the CREATE statements matching PATTERN
.selftest ?OPTIONS?      Run tests defined in the SELFTEST table
.separator COL ?ROW?     Change the column and row separators
.sha3sum ...             Compute a SHA3 hash of database content
.shell CMD ARGS...       Run CMD ARGS... in a system shell
.show                    Show the current values for various settings
.stats ?on|off?          Show stats or turn stats on or off
.system CMD ARGS...      Run CMD ARGS... in a system shell
.tables ?TABLE?          List names of tables matching LIKE pattern TABLE
.testcase NAME           Begin redirecting output to 'testcase-out.txt'
.testctrl CMD ...        Run various sqlite3_test_control() operations
.timeout MS              Try opening locked tables for MS milliseconds
.timer on|off            Turn SQL timer on or off
.trace ?OPTIONS?         Output each SQL statement as it is run
.vfsinfo ?AUX?           Information about the top-level VFS
.vfslist                 List all available VFSes
.vfsname ?AUX?           Print the name of the VFS stack
.width NUM1 NUM2 ...     Set column widths for "column" mode
sqlite> select * from sqlite_master where name =='myDB';
table|myDB|myDB|2|CREATE TABLE myDB(name text not null, age int, address char(50))
sqlite> .save data1 (이거를 붙여서 원하는 파일이름으로 저장을 하고 아나콘다와 같은 경로에 저장한다.)

참고로 sql언어에서는 " " 가 아니라 ' '를 사용한다.
이제 이걸 아나콘다에서 열어본다.

import sqlite3

conn=sqlite3.connect("data1")
cur=conn.cursor() #데이터를 가져오기 위한 커서를 만든다.
cur.execute("select * from myDB") #실행결과가 커서에 담긴다.
cur.execute("select * from myDB where age >10") #myDB에 있는 age칼럼이 10이상인 것만 출력하기
rows=cur.fetchall()
for row in rows:
    print(row)
    
conn.close()

이래하면 

('park', 10, 'seoul')
('lee', 20, 'dagu')

이래 나온다.


cur.execute("select * from myDB where age >10") #myDB에 있는 age칼럼이 10이상인 것만 출력하기

이렇게도 할 수 있다.



아까한거는 데이터 베이스에 값을 직접 넣어주었다
이번엔 텍스트에 있는 내용을 데이터베이스에 넣는 방식이다.

이건 insert를 사용한다. 다음과 같이한다. 복잡하지만 해보면 도움이 된다.

import sqlite3

def viewdb(db,table):
    conn=sqlite3.connect(db)
    cur=conn.cursor()
    query="select * from {0}".format(table)
    cur.execute(query)
    #cur.execute("select * from myDB where age >10") #myDB에 있는 age칼럼이 10이상인 것만 출력하기
    rows=cur.fetchall()
    for row in rows:
        print(row)
        
    conn.close() #cur.close()와 어떤차이? =결과는 같음 ㄷㄷ.

def savedbtable(db,data):
    conn=sqlite3.connect(db)
    cur=conn.cursor()
    sql= "insert into myDB(name, age, address) values (?, ?, ?)" #새로운 데이터를 넣는다
    cur.executemany(sql,data)
    
    conn.commit() #수정할 내용을 반영한다
    conn.close()

if __name__=='__main__':
    f= open('dbtext.txt','r')
    mat=[[0]*3 for row in range(3)] #3x3 배열만들기
    tempfile=f.read().splitlines() #텍스트 파일을 읽는다.
    
    for i, tf in enumerate(tempfile): #순서대로 정렬된 파일을 읽는것
        for j,savefile in enumerate(tf.split()):
            mat[i][j]=savefile
            
    f.close()
    
    savedbtable('data1',mat)
    viewdb('data1','myDB')

하면

('oaks', 30, 'ulsan')
('oaks', 30, 'ulsan')
('oaks', 30, 'ulsan')
('han', 22, 'seoul')
('eum', 20, 'seoul')
('dong', 22, 'seoul')

이래 나온다.




다음번엔 덩치가가장 크고 잘 알려진 mysql을 사용해 본다.

댓글