Skip to content
Advertisement

Insert string at particular location on a loop

I have a csv file containing product numbers and I need to insert these into a string which will be later used as a SQL query. I can read and append the values fine but I cant format it correctly.

import csv

query = 'SELECT * FROM Products WHERE prodNum ='

with open('numbers.csv') as csvfile:
    readCSV = csv.reader(csvfile, delimiter=',')
    for row in readCSV:
        num = "prodNum = "+(row[0] )
        query += num

print(query)

The problem is I need to insert the read value into () , if the file had 3 values, I need the output to be like the below for example

SELECT * FROM Products WHERE (prodNum = 111) OR (prodNum = 222) OR (prodNum = 333)

Advertisement

Answer

Not sure if I understood correctly what you are trying to do, but maybe this does the trick?

query = 'SELECT * FROM Products WHERE '

with open('numbers.csv') as csvfile:
    readCSV = csv.reader(csvfile, delimiter=',')
    for row in readCSV:
        num = "(prodNum = "+row[0]+") OR "
        query += num
query = query[:-4]
print(query)
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement