본문 바로가기

Program

Python MySQL 사용법

반응형

Python MySQL 사용법

 
pip 모듈이 설치되어있다고 가정하고 아래 명령어를 입력하여 mysql-connector를 설치한다.
 
sudo pip install mysql-connector-python

MySQL Connector를 이용하여 SELECT, INSERT 활용.

# -*- coding: utf-8 -*-
import mysql.connector

class MySqlDataProvider:
def __init__(self):
self.con = None
self.cursor = None

def connect(self):
if self.con is None:
self.con = mysql.connector.connect(host='mysql_ip', port='mysql_port', database='dbname', user='mysql_id', password='mysql_pw')
self.cursor = self.con.cursor()


def disconnect(self):
if self.cursor is not None:
self.cursor.close()
if self.con is not None:
self.con.close()

# SELECT
def get_stat(self, p_key):
self.connect()
self.cursor.execute('select stat_value from stat where stat_key = %s', (str(p_key),))
m_rows = self.cursor.fetchall()
self.disconnect()

return m_rows

# INSERT
def set_stat(self, p_key, p_value):
self.connect()
self.cursor.execute('insert into `stat` (stat_key, stat_value) values (%s, %s);', (str(p_key), str(p_value)))
self.con.commit()
self.disconnect()




 

반응형

'Program' 카테고리의 다른 글

CentOS 8에 MySQL 설치하기  (0) 2020.11.24
Python logging 함수간에 공유하여 사용하기  (0) 2020.11.24
CentOS Python 3.6 설치  (0) 2018.09.03
ElasticSearch 쿼리  (0) 2018.06.18
CentOS7에 ElasticSearch 설치하기  (0) 2018.06.05