string.join question

Mark McEahern marklists at mceahern.com
Wed Oct 2 22:45:48 EDT 2002


> I'm accessing MySQL from Python. This is for an insert statement
> which looks like this:

Does your MySQL library have something that does this for you?  Something
like stored procedures in SQL Server?  You want to be careful with user
input so you don't allow something like this:

  last_value = "'mundane'; drop database 'foo';"

Realizing the above is an imperfect expression of a potential exploit and
ignoring the whole issue for now, consider this:

#!/usr/bin/env python

"""
This could easily be improved upon, etc.
"""

def quote(s):
  """Return value wrapped in single-quotation marks."""
  # Ignore the need to escape quotes for now.
  return "'%s'" % s

def insert_sql(tablename, columns, values):
  """Return INSERT statement."""
  sql_template = "insert into %(tablename)s (%(columns)s) values
(%(values)s);"
  columns = ','.join(columns)
  values = ','.join([quote(v) for v in values])
  return sql_template % locals()

tablename = 'foobar'
columns = ['field1', 'field2', 'field3']
values = ['a', 'b', 'c']

print insert_sql(tablename, columns, values)

Cheers,

// m





More information about the Python-list mailing list