2011-11-04 12 views
0

私は以下のデータ構造(辞書)を構築しました。私は保持場所としてPython辞書を使用しています。Python:SQLクエリを辞書に保存する(Bit複雑なデータ構造)

325167 A, 
953929 B, A, C 
824420 D, B, 
796992 K, M, Z, 
825116 J, F, E, 

私は、それぞれの値を取り、データベースにクエリを送信し、結果はどこsome_table.someColは=「A」some_tableから何かを選択します。次に、このデータを別の辞書に保存して、将来使用するようにしています。

これは私が現在取り組もうとしているエラーです.cl_toは、フォーカスしているクエリの列名です。

Traceback (most recent call last): 
    File "Category.py", line 148, in <module> 
    categoryResults.append(categoryRow['cl_to']); 
TypeError: 'NoneType' object is not subscriptable 
{'cl_to': 'EP-plater_etter_\xc3\xa5r'} 
{'cl_to': 'Musikk_i_2002'} 
None 

これは私のコードがどのように見えるかです:

#Dictionary to save initial category with the rest of cl_to 
baseCategoryTree = {} 
categoryResults = [] 

# query get all the categories a category is linked to 
categoryQuery = "select cl_to from sometable cl left join anotherTable p on cl.cl_from = p.another_column where p.some_column=14 and p.another_column ='"; 
cursor = db.cursor(cursors.SSDictCursor); 

    for key, value in idTitleDictionary.iteritems(): 
     for startCategory in value[0]: 
      #print startCategory + "End of Query"; 
      try: 
       baseCategoryTree[startCategory] = []; 
       #print categoryQuery + startCategory; 
       cursor.execute(categoryQuery + startCategory + "'"); 
       done = False; 
       while not done: 
        categoryRow = cursor.fetchone(); 
        print categoryRow; 
        if not categoryRow: 
         done = True; 
         continue; 
       categoryResults.append(categoryRow['cl_to']); 
       baseCategoryTree[startCategory].append(categoryResults); 
      except Exception, e: 
       traceback.print_exc(); 

ベスト。 N-H

答えて

1

に...

  while not done: 
       categoryRow = cursor.fetchone(); 
       print categoryRow; 
       if not categoryRow: 
        done = True; 
        continue; 
      categoryResults.append(categoryRow['cl_to']); 

...

continuecategoryRowはNoneにしようとしている時点で、それ以上のwhileに折り返されます。

続いたとき:

categoryRow['cl_to'] 

に遭遇した...ブーム。

...

  while not done: 
       categoryRow = cursor.fetchone(); 
       print categoryRow; 
       if not categoryRow: 
        done = True; 
        continue; 
       categoryResults.append(categoryRow['cl_to']); 

...

+0

しかし、私はすべての行を取得し続ける必要があります..?私は何かを逃していますか? –

+0

更新された回答を参照してください。 curser.fetchone()がNoneを返すと、フェッチする行はもうありません。 – astevanovic

+0

ありがとう、しかし、私はまだこの問題をすべてのクエリの結果は、辞書のすべての単一のキーに追加されて...私はここで間違って何を見ていないよ..任意の考え..? –

1

は、私はあなたがwhileループでcategoryResults.append(categoryRow['cl_to'])を意味だと思う:あなたはすべての行を取得したい場合は、

は、あなたはおそらく次のようにしたいです。さて、categoryRowNoneになるまでループしています。そして、追加して明白なエラーを取得しようとします。

ところで、行の最後に;をすべて取り除いてください。これはPythonであり、C/C++ではありません。あなたは、単一の行に二つの文をしたい場合;は唯一のように、必要とされています

do_some_thing(); do_some_other_thing() 

しかし、これは一般的に読みやすさのために悪いことです。代わりに別の行を使用してください。

do_some_thing() 
do_some_other_thing() 
関連する問題