首页  编辑  

Attach SQL数据库

Tags: /超级猛料/Database.数据库相关/SQL Server/   Date Created:

Function AttachDBFile2SqlServer(DBName,MDBFileName,LOGFileName:string;SaPassword:string=''):String;

// 返回数据库连接字符串 可以直接给ado用的  write by chenshaizi 2004-03-04 chenshaizi@163.com

Var Conn:TADOConnection;

Qry:TADOQuery;

Function ExecAttach:boolean;

begin

    Result:=false;

    with Qry do

    try

        RenameFile(LOGFileName,LOGFileName+'.BAK');//改名日志文件,以缩小数据库日志文件到504K

        sql.Text:='sp_attach_single_file_dB '+QuotedStr(DBName)+','+QuotedStr(MDBFileName);

        ExecSQL;

        DeleteFile(Pchar(LOGFileName+'.BAK'));// 成功后删除备份的日志文件

        Result:=true;

    except

         try //sql.Text不用改变,只是加上日志文件进行附加

            RenameFile(LOGFileName+'.BAK',LOGFileName);//日志改名后附件不成功,日志 改名回来

            ExecSQL;

            Result:=true;

         except

              try

                 Sql.Text:='sp_attach_db '+QuotedStr(DBName)+','+QuotedStr(MDBFileName)+','+QuotedStr(LOGFileName) ;

                 ExecSQL;

                 Result:=True;

              except

            end;

        end;

      end;

 end;

begin

try

  Result:='';

  DBName:=Trim(DBName);

  MDBFileName:=Trim(MDBFileName);

  LOGFileName:=Trim(LOGFileName);

  SaPassword:=Trim(SaPassword);

  Conn:=TADOConnection.Create(Application);

  Conn.LoginPrompt:=false;

  Qry:=TADOQuery.Create(Application);

  Qry.Connection:=Conn;

  with Conn do begin

       Conn.ConnectionString:='Provider=SQLOLEDB.1;Integrated Security=SSPI';

       try //NT认证

           open;

       except

           Conn.ConnectionString:='Provider=SQLOLEDB.1;Persist Security Info=False;User ID=sa';

           try //SA空密码

              open;

           except //SA需要密码

             if (SaPassword='') then

                SaPassword:=InputBox('SQL数据库需要密码','请输入SA的密码:','请注意此处密码为明文');//密码输入对话框可以用有自制的form*的

                Conn.ConnectionString:=' Provider=SQLOLEDB.1;Password='+SaPassword+';Persist Security Info=True;User ID=sa';

                 try

                   open;

                 except

                 end;

           end;

       end;

       if Connected and ExecAttach then

          with Qry do begin

              sql.Text:='select top 1 DataSource from Master.dbo.sysservers'; //取本机名字

              open;

              Result:=Fields[0].AsString;

              Result:=Conn.ConnectionString+';Initial Catalog='+DBName+';Data Source='+Result;

          end;

  end;//with Conn do begin

finally

 Conn.Free;

 Qry.Free;

end;

end;