0

我有这个从 mysql 表中检索数据的代码。我正在使用 Python 的 MySQLdb 模块。我希望在数组下检索基于 SELECT WHERE 条件的每个列的数据。例如,在下面的代码中,我希望在不同的数组下检索位置字段为“NY,US”的所有数据 - 每个数组代表不同的列值。

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()

有什么问题吗?

4

2 回答 2

2

python中有一个名为“list”的数据结构,您可以将其用作数组。如果您的问题的语义我理解的是“获取按列分类的数组中的结果,并存储在本地列表中”,那么您可以执行以下简单的实现:记住我已经一一获取了符合给定条件的行;作为一种良好的做法;

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()
于 2012-11-18T12:06:33.370 回答
0

一旦你有了resultsfrom cursor.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) ) 
于 2012-11-18T12:03:14.870 回答