1

How to convert python array like columns = ['column1', 'column2', 'column3'] for forming SQL statement like

"Select column1, column2, column3 from table" ?

I can use join on array but don't know how to get rid of quotes of string.

3
  • 1
    The quotes are not part of the string. They are a display aid. Commented Dec 14, 2018 at 19:25
  • The quotes are not the issue. You can't parameterize column names. You'll need to format them in. If this is front-facing, you'll need to check the user input against a list of valid names to prevent SQL injection Commented Dec 14, 2018 at 19:27
  • thank you @timgeb join works just fine. did not realize they are just display aid Commented Dec 14, 2018 at 19:50

1 Answer 1

2
>>> 'select ' + ', '.join([c for c in columns]) + ' from table'
'select column1, column2, column3 from table'

Is that what you have in mind?

Sign up to request clarification or add additional context in comments.

4 Comments

Yes somehow I believed join would not be sufficient but this works
@user1411335 remember that strings could contain sql injections when hacking together sql statements like this. It's better to use a robust library. You can start here.
@timgeb, no library will make the above secure, "robust" or no. Parameterized queries parameterize only data, not table or column names. Most SQL client libraries are similarly restricted. I suggest your caveat is misplaced because there's no data involved, no suggestion that the names come from the user, and that it's common programming practice for applications to have DBMS names hard-coded in them.
@JamesK.Lowden you clearly know more about this stuff than me, so I suggest that people listen to you on this matter.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.