[Tutor] String with literal %s

Steven D'Aprano steve at pearwood.info
Fri Mar 21 00:48:39 CET 2014


On Thu, Mar 20, 2014 at 04:18:35PM +0000, Alan Gauld wrote:
> On 20/03/14 14:46, Toni Fuente wrote:
> 
> >I am trying to create a string this way:
> >
> >insertion = "INSERT INTO mytable(week %s) VALUES (\%s, \%s)" % osStringI

Don't do this! The world has far too many software vulnerable to code 
injection attacks already, please don't add another one!

When you hear about the latest virus or malware that infects computers, 
they nearly always are due to a programmer messing up by writing buggy 
code. In this case, using % to build up SQL queries is a classic example 
of buggy code that is vulnerable to code injection.

http://xkcd.com/327/

http://bobby-tables.com/python.html


> >not enough arguments for format string
> >
> >Where the first %s is going to be substitute by the variable osStringI,
> >but the other two VALUES (\%s, \%s), should be created as literals '%s'.
> 
> 
> If you double the % sign it is treated as a percent character.
> 
> "INSERT INTO mytable(week %s) VALUES (%%s, %%s)"
> 
> But do you really want to do it this way?
> Wouldn't it be better to use the SQLite parameter insertion syntax
> and do it all at the execute stage?

It certainly would!


> cur.execute("INSERT INTO mytable(week ?) VALUES (?, ?)", val1,val2,val3)
> 
> just a thought,

A very good thought.



-- 
Steven


More information about the Tutor mailing list