通过C#删除SQL Server数据库
发布时间:2020-12-15 06:27:22 所属栏目:百科 来源:网络整理
导读:我使用这个代码通过C#删除数据库 Int32 result = 0;try{ String Connectionstring = CCMMUtility.CreateConnectionString(false,txt_DbDataSource.Text,"master","sa","happytimes",1000); SqlConnection con = new SqlConnection(); con.ConnectionString =
我使用这个代码通过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; 但是我收到一个错误
谁能帮忙? 解决方法
尝试这个:
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; (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |