首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 數據庫知識 >  >> DB2 資料庫 >> DB2 綜合知識

使用表單動態建構 SQL INSERT 陳述式:ASP/VBScript 完整實作

     編輯:DB2 綜合知識

從表單自動產生 INSERT SQL

展示一個通用的 VBScript 函數 buildSQLInsert,根據表單提交欄位動態組裝 INSERT 陳述式,支援欄位類型推斷(文字/數值)、NULL 處理、欄位排除清單。

核心函數邏輯

function buildSQLInsert(targetTable, omitFields)
  iStr = "insert into " & targetTable & " "
  vStr = "values ("
  nStr = "("

  for each x in request.form
    fieldName = uCase(x)
    if inStr(uCase(omitFields), x) = 0 then
      fieldData = replace(request.form(fieldName), "'", "")
      if trim(fieldData) = "" then
        fieldData = "NULL"
        vStr = vStr & fieldData & ", "
        nStr = nStr & fieldName & ", "
      else
        typeDelimPos = inStr(fieldName, "_")
        if typeDelimPos = 0 then
          ' 文字欄位
          nStr = nStr & fieldName & ", "
          vStr = vStr & "'" & fieldData & "', "
        else
          ' 含類型前綴欄位,如 NUM_AGE
          fieldType = left(fieldName, typeDelimPos - 1)
          fieldName = mid(fieldName, typeDelimPos + 1)
          nStr = nStr & fieldName & ", "
          select case uCase(fieldType)
            case "NUM"
              vStr = vStr & fieldData & ", "
            case else
              vStr = vStr & "'" & fieldData & "', "
          end select
        end if
      end if
    end if
  next

  vStr = left(vStr, len(vStr) - 2) & ")"
  nStr = left(nStr, len(nStr) - 2) & ") "
  buildSQLInsert = iStr & nStr & vStr
end function

表單欄位命名規範

  • 一般文字欄位:直接使用欄位名,如 fName、lName
  • 數值欄位:加 NUM_ 前綴,如 num_age → 對應欄位 age,不加引號
  • 排除欄位:第二參數傳入逗號分隔清單,如 "lname,fname"

測試表單範例

<form name=f method=post action="list4.asp">
  First Name: <input type=text name="fName"><br>
  Last Name: <input type=text name="lName"><br>
  Age: <input type=text name="num_age"><br>
  <input type="checkbox" value="Y" name="MyCheckBox"> Do you want this checked?<br>
  <input type="submit" value="Submit">
</form>

呼叫範例與輸出

response.write buildSQLInsert("", "")           ' 全欄位
response.write buildSQLInsert("", "NUM_AGE")    ' 排除 NUM_AGE
response.write buildSQLInsert("", "lname,fname") ' 排除 lname,fname
response.write buildSQLInsert("", "mycheckbox,fname") ' 排除 checkbox 與 fname

安全性提醒:此範例為教學示範,實際生產環境必須使用參數化查詢防止 SQL 注入,不可直接拼接使用者輸入。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved