Arturo Altamirano
Arturo Altamirano

Reputation: 15

Converting SQLite database column values to strings and concatenating

I have a database with the following format.

(1, 'Kristen', 'Klein', '2002-11-03', 'North Cynthiafurt', 'AZ', '50788')

I am trying to strip away the first and last name values and pass them to a function to concatenate them as strings. "Kristen Klein" in this case.

I use a query such as:

query_first = db.select([customer.columns.first_name])
proxy_first = connection.execute(query_first)
result_first = proxy_first.fetchall()
print(result_first)

to extract all the first name values and they come out like this: [('Kristen',), ('April',), ('Justin',)]

I use an identical one for the last names and get an identical output.

This syntax is confusing to me as it appears to be a dictionary (?). How do I convert these to strings so that I may concatenate them into a cohesive name?

Upvotes: 1

Views: 1258

Answers (3)

MattSom
MattSom

Reputation: 2377

There are some SQLAlchemy utilizing answers here. In that case:

SQLite don't understand func.concat, you have to use string addition operators.

from sqlalchemy import String
from sqlalchemy.sql.expression import cast

query = db.select(cast(customer.columns.first_name, String) + " " + cast(customer.columns.last_name, String))

Upvotes: 0

kite
kite

Reputation: 541

This [('Kristen',), ('April',), ('Justin',)] - is a list of tuples. If you are confused by the trailing comma after string, because it is required to distinguish it as a tuple for single element tuple's. Find out the full info here in python wiki.

I guess you were using sqlalchemy library to connect to the db. If so by selecting the last_name with your first_name would provide you with a result_set list at the end which is iterable in a for loop. So, by concatenating each tuple would give you the full name. Please find the changes below,

#input
query = db.select([customer.columns.first_name, customer.columns.last_name])
result_proxy = connection.execute(query)
result_set = result_proxy.fetchall()

for row in result_set:
    print(' '.join(row))
#output
Kristen Klein
Peter Parker
Tony Stark
...

Upvotes: 1

Yaakov Bressler
Yaakov Bressler

Reputation: 12098

You can also concatenate on the query level:

from sqlalchemy.sql import  functions as func

query = db.select(
    func.concat(
        customer.first_name, ' ', customer.last_name
    )
)
results = connection.execute(query).all()

Or write raw SQL:

raw_sql = """
    SELECT
        first_name || ' ' || last_name
    FROM
        customer
"""

results = connection.execute(raw_sql).all()

Upvotes: 0

Related Questions