时间:2021-07-01 10:21:17 帮助过:93人阅读
注意:文件的编码格式,最好要统一,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 时间 读取