Delphi 執行SQL指令碼/執行SQL GO 指令碼語句
阿新 • • 發佈:2020-09-16
Delphi 執行SQL指令碼/執行SQL GO 指令碼語句
注意:檔案的編碼格式,最好要統一,ANSI編碼或UNICODE編碼
方法1:
var s: string; sqltext: string; sqlfile: TextFile; begin if OpenDialog1.Execute then begin AssignFile(sqlfile, OpenDialog1.FileName); FileMode := 0; Reset(sqlfile); try ADOConnection1.BeginTrans; while not eof(sqlfile) do begin Readln(sqlfile, s); sqltext := s; while (not eof(sqlfile)) and (uppercase(trim(s)) <> 'GO') do begin Readln(sqlfile, s); if (uppercase(trim(s)) <> 'GO') then sqltext := sqltext + ' ' + s; end; adoquery1.Close; adoquery1.SQL.Clear; adoquery1.SQL.Add(sqltext); adoquery1.ExecSQL; end; CloseFile(sqlfile); ADOConnection1.CommitTrans; application.MessageBox('SQL執行完成!', '提示', MB_OK + MB_ICONINFORMATION); except raise exception.Create('SQL執行失敗!'); ADOConnection1.RollbackTrans; end; end; end;
方法2:(這裡要注意:指令碼語句中 go 一定要換行)
var I: Integer; S: string; begin with TStringList.Create do try LoadFromFile('test.sql'); S := ''; for I := 0 to Count - 1 do begin if SameText(Trim(Strings[I]), 'GO') then begin // SameText 不區分大小寫 讀取到GO 就執行一次程式碼 with ADOQuery1 do begin Close;SQL.Clear; SQL.Text:=sSQL; ExecSQL; end; S := ''; end else S := S + Strings[I] + #13#10; end; if S <> '' then begin with ADOQuery1 do begin Close;SQL.Clear; SQL.Text:=sSQL; ExecSQL; end; end; finally Free; end; end;
建立時間:2020.09.16 更新時間: