2013-10-27 114 views
0

我想創建一個格式化在Python中的查詢,我想不出如何我可以字符串轉義數據的二進制輸入。它返回如下內容:Python格式化字符串轉義

INSERT INTO pythonUDPPacketDestinationSourceProtocolVersionHeader_LengthTTLProtoco l_UDPTargetSource_PortDestination_PortLength)VALUES(NULL,'00:0C:29:B2:14:0℃下」, '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 '');)

你怎麼能正確地逃避與蟒蛇格式的二進制字符串值?

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) 
+0

你用什麼數據庫適配器? –

回答

2

不要對SQL查詢使用格式。使用SQL參數而不是

然後,您的數據庫適配器會爲您處理轉義的,前提是它可以處理二進制數據。

您如何格式化SQL參數取決於所使用的數據庫; sqlite3的使用?佔位符:

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

,你會在值列表傳遞的第二個參數cursor.execute()方法:

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

你需要你的數據庫適配器文檔以驗證什麼支持style of SQL parameters(一個或多個?,%s,:1,:name%(name)s)以及它如何處理二進制值。

如果根本不處理二進制值,則需要將該二進制值解碼爲unicode值;或許使用base64編碼,或者使用Latin-1進行解碼,以獲得Unicode代碼點的一對一轉換。

6

萬一有人搜索該主題,並得到了領導到這裏

這是你如何逃脫「格式」:

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

因此,{{}}被逃了出來,還原爲{}