我使用这个代码通过C#删除数据库
Int32 result = 0; try { String Connectionstring = CCMMUtility.CreateConnectionString(false,txt_DbDataSource.Text,"master","sa","happytimes",1000); sqlConnection con = new sqlConnection(); con.ConnectionString = Connectionstring; String sqlCommandText = "DROP DATABASE [" + DbName + "]"; if (con.State == ConnectionState.Closed) { con.Open(); sqlConnection.ClearPool(con); con.ChangeDatabase("master"); sqlCommand sqlCommand = new sqlCommand(sqlCommandText,con); sqlCommand.ExecuteNonQuery(); } else { con.ChangeDatabase("master"); sqlCommand sqlCommand = new sqlCommand(sqlCommandText,con); sqlCommand.ExecuteNonQuery(); } con.Close(); con.Dispose(); result = 1; } catch (Exception ex) { result = 0; } return result;
但是我收到一个错误
Database currently in use
谁能帮忙?
解决方法
尝试这个:
String sqlCommandText = @" ALTER DATABASE " + DbName + @" SET SINGLE_USER WITH ROLLBACK IMMEDIATE; DROP DATABASE [" + DbName + "]";
还要确保您的连接字符串默认您为主数据库,或任何其他数据库,而不是您正在丢弃!
除此之外,你真的不需要所有关于你的查询的东西. ConnectionState将始终从“关闭”开始,因此您不需要检查它.同样,将连接封装在使用块中,无需明确地关闭或处理连接.你真正需要做的是:
String Connectionstring = CCMMUtility.CreateConnectionString(false,1000); using(sqlConnection con = new sqlConnection(Connectionstring)) { con.Open(); String sqlCommandText = @" ALTER DATABASE " + DbName + @" SET SINGLE_USER WITH ROLLBACK IMMEDIATE; DROP DATABASE [" + DbName + "]"; sqlCommand sqlCommand = new sqlCommand(sqlCommandText,con); sqlCommand.ExecuteNonQuery(); } result = 1;