0

I execute the following code in my "app.py" and it works, while session.execute return not only the value of the cell but also characters like () and ,.

var = db.session.execute(text(f"SELECT city FROM world WHERE country = Germany")).fetchone()

without using fetchone(), the code showed me the memory address.

The output is ('Berlin',), How can I get only Berlin?

OmT
  • 59
  • 4

2 Answers2

0

I could not find an exact command instead of fetchone() or fetchall() to provide the pure cell value Berlin.

However, with Regex I turn the ('Berlin',) to Berlin as bellow:

var = "('Berlin',)"
var = re.findall(r"[a-zA-Z\s]", var)
var = ''.join(var)
print(var)

I provide a white-space as maybe some cities names has two part with a space.

OmT
  • 59
  • 4
  • The output isn't the string "('Berlin',)". The output of fetchone() is a tuple, since the SQL could request more than one field. – Malcolm Feb 24 '23 at 22:30
  • 1
    "an exact command instead of fetchone() or fetchall() to provide the pure cell value Berlin" - That would be `.scalar()` – Gord Thompson Feb 24 '23 at 22:33
  • 1
    Dear @GordThompson, you are right, this is the true answer – OmT Feb 24 '23 at 23:14
0

Since the SQL could be returning multiple fields, fetchone is returning the results as a tuple. For example, if you changed your select to 'SELECT city, country...', you would have gotten back ('Berlin', 'Germany').

To extract just 'Berlin' use var[0].

Malcolm
  • 461
  • 2
  • 10