3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

DBからデータを取得して返り値にするときに詰まったこと

Last updated at Posted at 2020-12-24

(備忘録なので簡単に。より詳しい情報はドキュメントなどを参照ください)

##execute()の返り値

・sqlalchemyでDBに接続して、excute()でクエリを発行したとき、
 返ってくるのは'sqlalchemy.engine.result.ResultProxy'クラスの
 オブジェクト

・つまり、DBから取得した値をintやstrなどで返すためにはひと工夫が必要

↓↓↓例えばこんな感じ↓↓↓

    from sqlalchemy import create_engine
    # 余談だけど型アノテーションはちゃんとしよう。この関数宣言をまねしちゃダメだぞ
    def fetchUserIdFromDB(userName):
        # DB接続
        engine = create_engine('sqlite:///app.db')
        
        userId = []
        with engine.connect() as con:
            # クエリ発行
            rows = con.execute("select USER_ID from user_table where USER_NAME='{}'".format(userName))
            print(type(rows)) # -> <class 'sqlalchemy.engine.result.ResultProxy'>
            for row in rows:
                # 一行ずつ辞書化して・・・
                userDict = dict(row)

                # valueをint化して配列にpush!
                userId.push(int(userDict['USER_ID']))

        return userId
3
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
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?