3

我想通过 sql 语句删除数据库,我的代码使用 delphi XE 和 ADO 进行 DB 访问,服务器是 MSSQL

  aDBConnection.ConnectionString :=  'Provider=SQLOLEDB.1;Integrated    

                   Security=SSPI;Persist Security Info=False;Initial Catalog='
                   + DatabaseName + '; Data Source=' + Servername;      

  aDBConnection.Connected := true;  

  aQuery.Connection := aDBConnection;

  aQuery.add.sql (' drop database ' + DatabaseName );

  aQuery.Execsql.

使用此代码序列运行许多其他 sql 语句很好,但他拒绝删除数据库,因为声称“数据库正在使用”。

猜猜这是真的,因为我确实有一个与数据库的连接,但是如何做其他的,我需要查询将 sql 发送到服务器......

4

1 回答 1

2

不需要显式关闭连接,正如 TLama 所提到的,您只需要使用 USE来更改您的连接。也不需要关闭数据集,除非它们是用CursorLocation := clUseServer;打开的。即使在更改为master (Button_ChangeToMasterClick) 之后,您也可以编辑已经打开的数据集,但由于 CursorLocation 是 clUseClient,您甚至可以删除数据库。删除后编辑自然会导致错误。

Const
 aDatabaseName='DeleteMeAfterUse';

procedure TForm3.ButtonCreateOpen_Click(Sender: TObject);
var
  Ads: TAdodataset;
begin
  AC.ConnectionString := 'Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=master;Data Source=127.0.0.1';
  AC.Connected := true;
  AC.Execute('Create DataBase ' + aDatabaseName);
  AC.Execute('Use ' + aDatabaseName);  // change connection to 'DeleteMeAfterUse'
  AC.Execute('Create Table Test (ID int)'); // will be created in DeleteMeAfterUse
  AC.Execute('Insert into Test Values (1)');
  Ads := TAdodataset.Create(self); // Display data on surface
  // Ads.CursorLocation := clUseServer;  **
  // ** don't use clUseServer if you want to delete the database without closing the datasets
  // default is clUseClient

  With Ads do
  begin
    Connection := AC;
    CommandText := 'Select * from Test';
    Active := true;
  end;
  DataSource1.DataSet := Ads; // Conected to a DBGrid for editing
end;

procedure TForm3.Button_ChangeToMasterClick(Sender: TObject);
begin
  AC.Execute('Use master');  // change connection to master , any other database will work too
end;

procedure TForm3.Button_DropDatabaseClick(Sender: TObject);
begin
  AC.Execute('Drop Database ' + aDatabaseName);
end;
于 2013-09-24T14:42:49.920 回答