我想通过sql语句删除数据库,我的代码就是这样使用delphi XE和ADO进行数据库访问,服务器是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发送到服务器......
答案 0 :(得分:2)
没有必要明确关闭连接,正如TLama所提到的,只需要USE来更改连接。也不需要关闭数据集,除非用 CursorLocation:= clUseServer打开它们; 即使在更改为 master (Button_ChangeToMasterClick)之后,您也可以编辑打开数据集,但由于CursorLocation是clUseClient,你甚至可以DROP数据库。自然下降后编辑会导致错误。
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;