跳轉至正文

編碼食譜/SQL 編碼

來自華夏公益教科書,開放世界的開放圖書

對各種資料型別進行編碼以安全地用於 SQL 命令。

VBScript 解決方案

[編輯 | 編輯原始碼]
function SQLEncode (vInput)
	dim CurrentLocale
	select case VarType(vInput)
		case 0,1  ' empty, null
			SQLEncode = "NULL"
		case 2,3  ' integer, longint
			SQLEncode = vInput
		case 4,5  ' single, double
			CurrentLocale = GetLocale
			SetLocale ("en-us")
			SQLEncode = CStr(vInput)
			SetLocale (CurrentLocale)
		case 7    ' date
			SQLEncode = "#" & _
				DatePart("yyyy", vInput) & "-" & _
				DatePart("m",    vInput) & "-" & _
				DatePart("d",    vInput) & " " & _
				DatePart("h",    vInput) & ":" & _
				DatePart("n",    vInput) & ":" & _
				DatePart("s",    vInput) & "#"
		case 8    ' string
			SQLEncode = vInput
			SQLEncode = Replace (SQLEncode, chr(0), "")
			SQLEncode = Replace (SQLEncode, "'", "''")
			SQLEncode = "'" & SQLEncode & "'"
	end select

end function
華夏公益教科書