码迷,mamicode.com
首页 > 数据库 > 详细

Delphi 执行SQL脚本/执行SQL GO 脚本语句

时间:2020-09-18 02:53:51      阅读:48      评论:0      收藏:0      [点我收藏+]

标签:大小写   eof   box   end   编码格式   integer   exception   时间   读取   

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  更新时间:

 

Delphi 执行SQL脚本/执行SQL GO 脚本语句

标签:大小写   eof   box   end   编码格式   integer   exception   时间   读取   

原文地址:https://www.cnblogs.com/guorongtao/p/13678241.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!