[CV 프로그램 만들기] 8. python에서 mysql에 연결

 

pymysql 패키지를 통해서 mysql에 접속합니다.

 

hostOS에서 다음과 같이 pymysql을 설치해 줍니다.

 

pip install pymysql

 

 

위의 사진에서 왼쪽 패널에서처럼 dbtools라는 폴더를 하나 추가하고 하위에 connect_db.py를 새로 만들어 줍니다.

 

다음은 pymysql 연결 예제입니다.

 

import pymysql

conn = pymysql.connect(host="192.168.56.104", user="root", password="1234",
                       db="samsongDB", charset="utf8")  # 1. DB 연결
cur = conn.cursor() # 2. 커서 생성 (트럭, 연결로프)
sql = "CREATE TABLE IF NOT EXISTS userTable2(userId INT, userName CHAR(5))"
cur.execute(sql)

sql = "INSERT INTO userTable2 VALUES( 1 , '홍길동')";
cur.execute(sql)
sql = "INSERT INTO userTable2 VALUES( 2 , '이순신')";
cur.execute(sql)

cur.close()
conn.commit()
conn.close() # 6. DB 닫기 (=연결 해제)
print('OK~')

위의 코드를 먼저 작성해서, 테스트를 한번 해봅시다.

host의 주소는 guestOS의 ip를 확인해서 적어 넣어야 합니다. 마찬가지로 user, password, db는 Windows Server 2019에 설치된 MariaDB의 id와 password입니다.

 

데이터가 잘 저장 되었는지, heidi SQL로 접속해봅시다.

 

SHOW DATABASES;

 

USE samsongdb;

 

SHOW TABLES;

 

SELECT * FROM usertable2;

 

를 실행하니, 위의 그림과 같이 잘 저장이 되었습니다.

 

데이터 저장이 잘 되는 것을 확인했습니다.

 

 

heidiSQL를 종료하고, 데이터 조회 테스트를 해줍시다.

 

아래와 같이 코드를 작성하고, 데이터를 조회하는 테스트를 해봅시다.

 

import pymysql

conn = pymysql.connect(host="192.168.56.110", user="root", password="1234",
                       db="samsongDB", charset="utf8")  # 1. DB 연결

cur = conn.cursor() # 2. 커서 생성 (트럭, 연결로프)
sql = "SELECT * FROM userTable2"
cur.execute(sql)

rows = cur.fetchall()

print(rows)


cur.close()
conn.close() # 6. DB 닫기 (=연결 해제)
print('OK~')

F5로 코드 실행을 해보니, 터미널 창에서 데이터가 잘 조회되는 것을 확인했습니다.

 

DB연결을 클래스로 제어하려고 하니, 오류가 발생했습니다.

 

다음 시간에 계속하도록 하겠습니다.

 

import pymysql

class DBConn:
    def __init__(self, host='192.168.56.110', user='root', password='1234', db='samsongDB', charset='utf-8', kind='mysql'): #TODO: change default values
        if kind=='mysql':
            self.conn = pymysql.connect(host=host, user=user, password=password, db=db, charset=charset)
            self.cur = conn.cursor() # 2. 커서 생성 (트럭, 연결로프)
        else: #TODO: 다른 데이터베이스 업데이트 하기
            pass
    
    def __del__(self):
        try:
            self.cur.close()
            self.conn.commit()
            self.conn.close() # 6. DB 닫기 (=연결 해제)
        except Exception as e:
            print(e)
    
    def execute(self, sql):
        self.conn.execute(sql)
    

if __name__ =="__main__":
    # DB접속 예제코드
    cur = DBConn(host='192.168.56.110', user='root', password='1234', db='samsongDB', charset='utf-8', kind='mysql')
    
    sql = "CREATE TABLE IF NOT EXISTS userTable2(userId INT, userName CHAR(5))"
    cur.execute(sql)

    sql = "INSERT INTO userTable2 VALUES( 1 , '홍길동')"
    cur.execute(sql)

    sql = "INSERT INTO userTable2 VALUES( 2 , '이순신')"
    cur.execute(sql)
    
    print('OK~')

 

 

 

댓글

Designed by JB FACTORY