看板 Visual_Basic 關於我們 聯絡資訊
※ 引述《goodtau (goodtau)》之銘言: : 大家好 : 有兩個問題想要請問大家 : 一. : 假設只有一筆資料要寫入資料庫 : 我會 就在連線字串那打sql的語法 insert into : 但現在有多筆資料,要寫入資料庫 要怎麼寫呢? : 以及假設這個資料庫欄位是 1.2.3.~~10好了 共有10欄 : 但我這多筆資料 分別可能是 每個欄位都有 ; 或者只有1~6欄 : 再或者中間會空個幾欄(好比這筆資料 1~4欄有 5.8欄各是 null ,其他欄有資料這樣) : 要怎麼做呢? 我大概這樣做: sub InsertList(cmds as Collection) '''SQL模版 const SQLTemplate as string = _ "insert into <TName> (<FList>) values (<VList>)" '''欄位模版 const FListTemplate as string = _ ",<F1>,<F2>,<F3>,<F4>,<F5>,<F6>,<F7>,<F8>,<F9>,<F10>" '''值模版,值要稍微斟酌資料形態,若字串則加上單引號,若數字則不加單引號 const VListTemplate as string = _ ",'<V1>','<V2>','<V3>','<V4>','<V5>','<V6>','<V7>','<V8>'," _ "'<V9>','<V10>'" dim dict as FileSystemObject.Dictionary dim SQL as string dim i as long dim j as long for i = 1 to cmds.count '''取SQL模版 SQL = SQLTemplate FList = FListTemplate VList = VListTemplate '''取命令參數,在此則要注意,若型態統一為字串,或統一為數字, '''則可以寫迴圈處理欄位列及值列,否則要用select case敘述來處理. set dict = cmds.item(i) for j = 1 to 10 if dict.HasKey("F" & j) then FList = replace(FList, "<F" & j & ">", "F" & j) VList = replace(VList, "<V" & j & ">", dict.Item("F" & j)) else '''在此將SQL處理為視忽略欄為自動補值的模式. '''假如忽略欄需要自行補值,則以下須做適當調整. FList = replace(FList, ",<F" & j & ">", "") VList = replace(VList, ",<V" & j & ">", "") end if next j FList = mid(FList, 2) VList = mid(VList, 2) '''執行SQL if FList <> "" then dim conn as Database.Connection dim result as long SQL = replace(SQL, "<FList>", FList) SQL = replace(SQL, "<VList>", VList) conn.execute SQL, result doevents end if next i end sub -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 36.226.94.105 ※ 編輯: yauhh 來自: 36.226.94.105 (11/05 00:44) ※ 編輯: yauhh 來自: 36.226.94.105 (11/05 00:46)