See
See

Reputation: 81

Python formatting string escape

i'm trying for create a query with formatting in python, I can't figure out how i can string escape the binary input for data. It returns something like this:

INSERT INTO python.UDP (Packet, Destination, Source, Protocol, Version, Header_Length, TTL, Protoco l_UDP, Target, Source_Port, Destination_Port, Length) VALUES (NULL, '00:0C:29:B2:14:0C', '192.168.178.50', '8 ', '4', '20', '128', '17', '192.168.178.24', '52371', '8888', '29227', 'b'Data\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00 \x00\x00\x00\x00'');)

how can you properly escape the binary string value with formatting in python?

def setopUDP(destination, source, protocol, version, header_length, ttl, protocolEGP, target, source_port, destination_port, length, data):
query = ("INSERT INTO `python`.`UDP` (`Packet`, `Destination`, `Source`, `Protocol`, "
         "`Version`, `Header_Length`, `TTL`, `Protocol_UDP`, `Target`, `Source_Port`, "
         "`Destination_Port`, `Length`) VALUES (NULL, '{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}');)"
         .format(destination, source, protocol, version, header_length, ttl, protocolEGP, target, source_port, destination_port, length, data))


setopCON(query)  

Upvotes: 0

Views: 1650

Answers (2)

pochen
pochen

Reputation: 873

Just in case someone searched this topic and got led to here

This is how you do escape for "format":

>>> "{{}}{}".format(10)
'{}10'

so, {{}} is escaped and reduced to {}

Upvotes: 9

Martijn Pieters
Martijn Pieters

Reputation: 1121226

Don't use formatting for SQL queries. Use SQL parameters instead.

Your database adapter then takes care of the escaping for you, provided it can handle binary data.

How exactly you format SQL parameters depends on the database used; sqlite3 uses ? placeholder:

query = ("INSERT INTO `python`.`UDP` (`Packet`, `Destination`, `Source`, `Protocol`, "
         "`Version`, `Header_Length`, `TTL`, `Protocol_UDP`, `Target`, `Source_Port`, "
         "`Destination_Port`, `Length`) VALUES (NULL, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?))")

and you'd pass in the list of values as the second argument to the cursor.execute() method:

cursor.execute(query,
    (destination, source, protocol, version, header_length, ttl, protocolEGP, target, source_port, destination_port, length, data))

You'll need to verify in your database adapter documentation what style of SQL parameters are supported (one or more of ?, %s, :1, :name or %(name)s) and how it handles binary values.

If binary values are not handled at all, you'd need to decode that binary value to a unicode value instead; use base64 encoding perhaps, or decode from Latin-1 to get a one-on-one translation into Unicode codepoints.

Upvotes: 2

Related Questions