[PYTHON] Clogged when getting data from DB and making it a return value

(Since it is a memorandum, it is easy. For more information, refer to Documentation etc.)

Return value of execute ()

-When connecting to DB with sqlalchemy and issuing a query with execute () It will return the'sqlalchemy.engine.result.ResultProxy' class object

-In other words, some ingenuity is required to return the value obtained from the DB with int or str.

↓ ↓ ↓ For example, like this ↓ ↓ ↓

    from sqlalchemy import create_engine
 # As an aside, let's do type annotation properly. Don't imitate this function declaration
    def fetchUserIdFromDB(userName):
 #DB connection
        engine = create_engine('sqlite:///app.db')
        
        userId = []
        with engine.connect() as con:
 # Query issuance
            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:
 # Make a dictionary line by line ...
                userDict = dict(row)

 Int # value and push to array!
                userId.push(int(liquorDict['USER_ID']))

        return userId

Recommended Posts

Clogged when getting data from DB and making it a return value
When plotting time series data and getting a matplotlib Overflow Error
Make a decision tree from 0 with Python and understand it (4. Data structure)
From installing Flask on CentOS to making it a service with Nginx and uWSGI
Python-Read data from a numeric data file and calculate covariance
Create a decision tree from 0 with Python and understand it (3. Data analysis library Pandas edition)
Get an image from a web page and resize it
Read the function name from the DB and execute it dynamically
Create a temporary file with django as a zip file and return it
Get data from MySQL on a VPS with Python 3 and SQLAlchemy