I am trying to format a Python array as a string to be inserted into an SQL query. I want to be able to handle string and integer data but I cannot figure out how to to format the array. This is what I have right now
columns = ['owner_id', 23, 'activity', 'rest']
val_str = ', '.join("%s" % (v) for k, v in enumerate(columns))
print "INSERT INTO %s VALUES (%s)" % (table_name, val_str)
Results in:
INSERT INTO activity_analyzed VALUES (owner_id, 23, activity, rest)
I am trying to insert an if
structure so that I can check the type of the variable and surround it with quotes if it is a string using typeof()
. However I am new to Python and I cannot seem to get the syntax right so that it works and does not give me an error. Something like this would be ideal:
val_str = ', '.join(
if type(v) is str:
"'%s'" % (v)
else if type(v) is int:
"%s" % (v)
for k, v in enumerate(columns)
)