通过C#删除SQL Server数据库

前端之家收集整理的这篇文章主要介绍了通过C#删除SQL Server数据库前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我使用这个代码通过C#删除数据库
  1. Int32 result = 0;
  2.  
  3. try
  4. {
  5. String Connectionstring = CCMMUtility.CreateConnectionString(false,txt_DbDataSource.Text,"master","sa","happytimes",1000);
  6.  
  7. sqlConnection con = new sqlConnection();
  8. con.ConnectionString = Connectionstring;
  9.  
  10. String sqlCommandText = "DROP DATABASE [" + DbName + "]";
  11. if (con.State == ConnectionState.Closed)
  12. {
  13. con.Open();
  14. sqlConnection.ClearPool(con);
  15. con.ChangeDatabase("master");
  16. sqlCommand sqlCommand = new sqlCommand(sqlCommandText,con);
  17. sqlCommand.ExecuteNonQuery();
  18. }
  19. else
  20. {
  21. con.ChangeDatabase("master");
  22. sqlCommand sqlCommand = new sqlCommand(sqlCommandText,con);
  23. sqlCommand.ExecuteNonQuery();
  24. }
  25.  
  26.  
  27.  
  28. con.Close();
  29. con.Dispose();
  30. result = 1;
  31. }
  32. catch (Exception ex)
  33. {
  34. result = 0;
  35. }
  36. return result;

但是我收到一个错误

Database currently in use

谁能帮忙?

解决方法

尝试这个:
  1. String sqlCommandText = @"
  2. ALTER DATABASE " + DbName + @" SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
  3. DROP DATABASE [" + DbName + "]";

还要确保您的连接字符串默认您为主数据库,或任何其他数据库,而不是您正在丢弃!

除此之外,你真的不需要所有关于你的查询的东西. ConnectionState将始终从“关闭”开始,因此您不需要检查它.同样,将连接封装在使用块中,无需明确地关闭或处理连接.你真正需要做的是:

  1. String Connectionstring = CCMMUtility.CreateConnectionString(false,1000);
  2.  
  3. using(sqlConnection con = new sqlConnection(Connectionstring)) {
  4. con.Open();
  5. String sqlCommandText = @"
  6. ALTER DATABASE " + DbName + @" SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
  7. DROP DATABASE [" + DbName + "]";
  8. sqlCommand sqlCommand = new sqlCommand(sqlCommandText,con);
  9. sqlCommand.ExecuteNonQuery();
  10. }
  11. result = 1;

猜你在找的C#相关文章