2016-06-02 2 views
1

어떻게 객체 지향 프로그래밍에서 파이썬으로 mysql로 ​​데이터를 전달할 수 있습니까? 모든 반에서 연결해야합니까?객체 지향 프로그래밍에서 데이터를 mySQL로 가져 오는 방법은 무엇입니까?

는 업데이트 :

이 내 목적은

class AttentionDataPoint(DataPoint): 
    def __init__ (self, _dataValueBytes): 
     DataPoint._init_(self, _dataValueBytes) 
     self.attentionValue=self._dataValueBytes[0] 

    def __str__(self): 
     if(self.attentionValue): 
      return "Attention Level: " + str(self.attentionValue) 

class MeditationDataPoint(DataPoint): 
    def __init__ (self, _dataValueBytes): 
     DataPoint._init_(self, _dataValueBytes) 
     self.meditationValue=self._dataValueBytes[0] 

    def __str__(self): 
     if(self.meditationValue): 
      return "Meditation Level: " + str(self.meditationValue) 

을 orinted 내가이 코딩을 사용하여 MySQL의에 데이터를 얻을하려고합니다.

import time 
import smtplib 
import datetime 
import MySQLdb 

db = MySQLdb.connect("192.168.0.101", "fyp", "123456", "system") 
cur = db.cursor() 

while True: 
    Meditation_Level = meditationValue() 
    Attention_Level = attentionValue() 
    current_time = datetime.datetime.now() 

    sql = "INSERT INTO table (id, Meditation_Level, Attention_Level, current_time) VALUES ('test1', %s, %s, %s)" 
    data = (Meditation_Level, Attention_Level, current_time) 
    cur.execute(sql, data) 
db.commit() 

db.close() 

업데이트 :

DataPoint에

class DataPoint: 
def __init__(self, dataValueBytes): 
self._dataValueBytes = dataValueBytes 
+0

당신은 당신의 연결을 재사용 할 수 있습니다 (그리고 당신이해야) 물론 : 파이썬

가장 인기 SQLAlchemy의입니다. 코드를 보여주십시오. – Raptor

+0

@Raptor 이미 코드를 업데이트합니다. – Hazim

+0

DataPoint의 정의는 무엇입니까? – olivecoder

답변

0

내가 연결하는 기능을 가진 클래스 같은 것을 생각하고 당신은 당신이 필요로하는 모든 클래스에 해당 클래스의 인스턴스를 전달 연결 (여기서는 db 인스턴스), 그렇지 않을 수도 있습니다! 다른 언어로 사용한 것입니다.

0

몇 가지 옵션 :

  • 각 클래스의 요구에 따라 선택/삽입/업데이트 SQL 명령을 구축하기 위해 각 DataPoint에 아이를위한 저장 /로드 방법을 구현합니다. 기본 자습서는 다음과 같습니다. Python MySQL Database Access
  • 클래스 속성에서 자동으로 위의 sql 명령을 빌드하는 클래스를 구현합니다.
  • 위라고 객체 관계형 매핑하고, 그래서, 당신은 바퀴 재발견 할 필요가 없습니다 : 그것은 큰되기 위해 어떤 기회와 간단한 프로젝트의 경우 https://www.fullstackpython.com/object-relational-mappers-orms.html

내가 첫번째로 갈 것을 다른 모든 경우에는 ORM 도구를 사용하십시오. http://docs.sqlalchemy.org/en/latest/orm/tutorial.html

+0

그냥 간단한 프로젝트입니다. 그래서 첫 번째 옵션을 사용할 것입니다. 나를 도울 수있는 자습서가 있습니까? – Hazim

관련 문제