LoginSignup
4
2

More than 1 year has passed since last update.

SQLで取得したデータがリスト型になってしまう問題(Python)

Last updated at Posted at 2018-09-12
id data
1 cat
2 dog
3 bird

PythonでSQLを使ってデータを取得し、データをプログラムで使う時の注意点です。
今回はidを入力し、対応するdataを一つだけ取得します。その場合

animal.py
sql = "SELECT animal FROM animal WHERE id = 1;"
animal = fetch_db(sql)  # オリジナル関数(sqlを実行してデータを取得する)

if animal == "cat":
    print("にゃー")

とすれば取得できそうです。
しかし、これではanimalの中身が [('cat',)] というリストになってしまいます。

文字列にするには、以下のようにデータを加工します。

animal.py
animal_list = fetch_db(sql)
animal_str = animal_list[0][0]

うしろに2つ[0]をつけます。
animal_list[0] だと、中身は ('cat',) というタプルになります。
animal_list[0][0] とすることで、中身が cat という文字列になります。

ちなみに、もし取得したデータが数値だった場合、中身は数値型になるので注意しましょう。

4
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
2