Search code examples
pythonpostgresqlsql-injectionpsycopg2formatted-input

Prevent sql injection with lists in python


So I have a list of formatted strings that i want to insert into a database, They are formatted so the database will accept this type of string.

Here is an example of the format:

mylist = [('123456789'), ('987654321'), ('1234554321'),....('9999999999')]
mylist[0] = ('123456789')

The format must be kept to ensure they are entered correctly.

I want to ensure that it is secure against sql injection,

I know this works:

database = connection.cursor()
for data in mylist:
    command = " INSERT INTO my_table(my_value) VALUES %s" %data
    database.execute(command)
connection.commit()

However I'm unsure if this is correct way to prevent sql injection

What I would prefer to do but it wont work is:

database = connection.cursor()
for data in mylist:
    command = " INSERT INTO my_table(my_value) VALUES %s"
    database.execute(command, (data))
connection.commit()

The error I receive is:

'str' object is not callable

I've seen online here that this is correct so why wont it work


Solution

  • Very hard to understand what you mean. This is my try:

    mylist = ['123456789','987654321','1234554321','9999999999']
    mylist = [tuple(("('{0}')".format(s),)) for s in mylist]
    records_list_template = ','.join(['%s'] * len(mylist))
    insert_query = '''
        insert into t (s) values
        {0}
    '''.format(records_list_template)
    print cursor.mogrify(insert_query, mylist)
    cursor.execute(insert_query, mylist)
    conn.commit()
    

    Output:

    insert into t (s) values
    ('(''123456789'')'),('(''987654321'')'),('(''1234554321'')'),('(''9999999999'')')
    

    The inserted tuples:

    select * from t;
           s        
    ----------------
     ('123456789')
     ('987654321')
     ('1234554321')
     ('9999999999')