引用自:https://blog.csdn.net/zhaoya_huangqing/article/details/48036839
一、在組成SQL語句並發送命令時完全按照Python中的樣式去傳遞,這樣在MySql中執行的時候就會遇到錯誤的命令,由單引號或者雙引號引起。因此應該在組成字符串之前,手動將字符串中的單引號或者雙引號之前加上反斜杠,這樣在組合成字符串的時候,MySql就能夠識別了。
例如:
str="""select count(*) from %s where %s.AppId="%s" """%(self._TB_NAME,self._TB_NAME,appid)
print str
cur.execute("%s"%(str))
如果appid是一種含有單引號或者雙引號的變量,例如 I'm XXX and say "hi!"
在這個變量中含有單引號,雙引號。這樣組成的SQL語句為:
select count(* )from table where table.AppId =" I'm XXX and say "hi!""
這樣的話,這個SQL語句明顯就會出錯。
因此在組成str之前應該對appid中的單引號雙引號進行處理。
使用replace方法將單引號和雙引號前面加上反斜杠。
appid=appid.replace("'","\\\'") 將單引號轉成\單引號
appid=appid.replace('"','\\\"') 將雙引號轉成\雙引號
這樣在組成的SQL語句就成了
select count(* )from table where table.AppId =" I\'m XXX and say \"hi!\""
這樣MySql就將字符串中的單引號雙引號正確識別了。
二、python向mysql數據庫插入數據時經常會碰到一些特殊字符,如單引號,雙引號。
解決辦法:
cur.execute(u'''update table set name = %s where id = %s;''' , (name.decode('utf-8'),index))
舉例:
name="I'mHere"
注意: cursor.execute()可以接受一個參數,也可以接受兩個參數:
(1) cur.execute("insert into resource(cid,name) values(%s, %s)" , (12,name) );
這種格式是接受兩個參數,MySQLdb會自動替你對字符串進行轉義和加引號,不必再自己進行轉義,執行完此語句之后,resource表中多了一條記錄: 12 I'mHere
(2) cur.execute("insert into resource(cid,name) values(%s, %s)" % (12,name) );
這種格式是利用python的字符串格式化自己生成一個query,也就是傳給execute一個參數,此時必須自己對字符串轉義和增加引號,即上邊的語句是錯誤的,應該修改為:
name = MySQLdb.escape_string(name);
cursor.execute("insert into resource(cid,name) values(%s, '%s')" % (12,name) );
這樣插入的記錄才和(1)一樣:12 I'mHere
解決辦法:
cur.execute(u'''update table set name = %s where id = %s;''' , (name.decode('utf-8'),index))
舉例:
name="I'mHere"
注意: cursor.execute()可以接受一個參數,也可以接受兩個參數:
(1) cur.execute("insert into resource(cid,name) values(%s, %s)" , (12,name) );
這種格式是接受兩個參數,MySQLdb會自動替你對字符串進行轉義和加引號,不必再自己進行轉義,執行完此語句之后,resource表中多了一條記錄: 12 I'mHere
(2) cur.execute("insert into resource(cid,name) values(%s, %s)" % (12,name) );
這種格式是利用python的字符串格式化自己生成一個query,也就是傳給execute一個參數,此時必須自己對字符串轉義和增加引號,即上邊的語句是錯誤的,應該修改為:
name = MySQLdb.escape_string(name);
cursor.execute("insert into resource(cid,name) values(%s, '%s')" % (12,name) );
這樣插入的記錄才和(1)一樣:12 I'mHere
三、如果要插入空值可以用如下方法
a = None
cur.execute("insert into resource(cid,name) values(%s, %s,%s)" , (12,name,a) );