打印本文 打印本文 关闭窗口 关闭窗口
Delphi 7 在程序中直接执行SQL脚本文件
作者:武汉SEO闵涛  文章来源:敏韬网  点击数1084  更新时间:2007/11/14 12:54:01  文章录入:mintao  责任编辑:mintao

在处理MSDE一些操作中。需要执行一些SQL脚本。有的是从
SQLServer 2000中生成的SQL为后缀的脚本。在MSDE中没有企业管理器,
操作都是在程序中完成的。所以用以下函数来执行SQL脚本。

//执行一个SQL角本文件,文件只能是ANSI编码的。
//如果文件是UNICODE编码的话,则会乱码。
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;

其中:ADOConnection1,adoquery1,OpenDialog1都是窗口中放置的控件。可以将之设为局部变量,在本函数内创建和消毁。

20:03:52

打印本文 打印本文 关闭窗口 关闭窗口