Home > front end >  how to use a list of strings in a sql query
how to use a list of strings in a sql query

Time:06-30

Alright, I have tried here this but it clearly doesn't work, I tried to find a similar question, but I didn't find the answer I seek, hence I ask here.

First of all, I have a list of strings that I've made from df columns:

list_cols=df_cols['COLUMN_NAME'].values.tolist()
list_cols

In this list, I got names that I want to put in a sql query selection

sql=(f'''select
        {list_cols}
    from
        big
    where
        date = '20220501'
''')
sql

However it returns:

"select\n        ['DATES', 'ID', 'ID2', ... , 'ID100']\n    from\n        big\n    where\n        date= '20220501'\n"

How can I avoid the '' and [] which is the problem with this query?

PS.: the list has more than 100 variables. I could use other methods to do this task such as puting into an excel sheet and selecting the text I want, but I wanna know a way using python codes.

CodePudding user response:

This code below should do the trick. Just use ','.join(list_cols) instead of list_cols only.

sql=(f'''select
        {','.join(list_cols)}
    from
        big
    where
        date = '20220501'
''')

Check out the output:

select
        DATES,ID,ID2,ID3,ID4,ID5,ID100
    from
        big
    where
        date = '20220501'

CodePudding user response:

you musst used strip and ",".join(",") to change String to ist

  • Related