2012-11-17 5 views
0

이 코드는 mysql 테이블에서 데이터를 가져옵니다. 파이썬의 MySQLdb 모듈을 사용하고 있습니다. SELECT WHERE 조건을 기반으로 각 열의 데이터를 배열 아래에서 검색해야합니다. 예를 들어, 아래 코드에서 위치 필드가 'NY, US'인 모든 데이터를 다른 배열에서 검색하려고합니다. 각 배열은 다른 열 값을 나타냅니다.Python 가져 오기 MySQL에서 배열로 데이터 열

import numpy 
import MySQLdb 

db = MySQLdb.connect("localhost", "root", "", "test") 
cursor = db.cursor() 

sql = "SELECT * FROM usa_new WHERE location = 'NY, US'" 
try: 
    cursor.execute(sql) 
    results = cursor.fetchall() 
    discresults = {} 
    for row in results: 

     id = row[0] 
     location = row[1] 
     temp_f = row[2] 
     pressure_mb = row[3] 
     wind_dir = row[4] 
     wind_mph = row[5] 
     relative_humidity = row[6] 
     timestamp = row[7] 

except: 
    print "Error: unable to fecth data" 

db.close() 

문제가 있습니까?

+0

거기에 'discresults {}'란 무엇입니까? – noel

+0

커밋() 메서드를 사용하여 쿼리를 완료해야한다고 생각합니다. – noel

+0

@shakabra acutallyy 나는이 코드를 조금 편집했다. 이전에는 각 열에서 단일 값을 꺼내고 있었다. 그래서 discresults가 여기에 있습니다. – khan

답변

1

당신이 배열로 사용할 수 있습니다 파이썬에서 '목록'라는 데이터 구조가 있습니다. 내가 이해 한 질문의 의미가 "열로 분류 된 결과를 로컬 목록에 저장하려면"다음과 같이 간단하게 구현할 수 있습니다. 주어진 기준에 일치하는 행을 하나씩 가져 왔음을 기억하십시오. ; 좋은 연습으로.

import MySQLdb 

db = MySQLdb.connect("localhost", "root", "", "test") 
cursor = db.cursor() 
id, location, temp_fm, pressure_mb, .. = [],[],[],[],... 
//for the number of lists you want to create, just add their names and a empty list 
sql = "SELECT * FROM usa_new WHERE location = 'NY, US'" 

try: 
    cursor.execute(sql) 

    rcount = int(cursor.rowcount) 

    for r in rcount: 
     row = cursor.fetchone() 

     id.append(row[0]) 
     location.append(row[1]) 
     temp_f.append(row[2]) 
     pressure_mb.append(row[3]) 
     wind_dir.append(row[4]) 
     wind_mph.append(row[5]) 
     relative_humidity.append(row[6]) 
     timestamp.append(row[7]) 

except: 
    print "Error: unable to fecth data" 

db.close() 
0

당신이 당신의 resultscursor.fetchall()에서, 당신이 NumPy와 배열에 결과를 매핑을 시도 할 수 있습니다 일단 : -

cols = zip(*results) # return a list of each column 
         # (the * unpacks the 1st level of the tuple) 
outlist = [] 

for col in cols: 

    arr = numpy.asarray(col) 

    type = arr.dtype 

    if str(type)[0:2] == '|S': 
     # it's a string array! 
     outlist.append(arr) 
    else: 
     outlist.append(numpy.asarray(arr, numpy.float32)) 
관련 문제