Skip to main content
 首页 » 编程设计

c#之如何删除一个表

2024年02月06日12lhb25

我正在使用以下 C# 方法来执行 SQL查询:

public bool ExecuteQuery(String pQuery) 
{ 
    SqlConnection con = new SqlConnection("MyConnectionString"); 
    con.Open(); 
 
    SqlTransaction trans = con.BeginTransaction(IsolationLevel.ReadCommitted); 
 
    try 
    { 
        SqlCommand cmd = new SqlCommand(pQuery, con, trans); 
        cmd.ExecuteNonQuery(); 
        trans.Commit(); 
        con.Close(); 
        trans.Dispose(); 
        return true; 
    } 
    catch (Exception exp) 
    { 
        trans.Rollback(); 
        con.Close(); 
        MessageBox.Show(exp.Message, "Error!!", MessageBoxButtons.OK, MessageBoxIcon.Error); 
    } 
 
    return false; 
} 

当我通过这条语句时:

ExecuteQuery("DROP TABLE MyTable"); 

然后该方法返回 true,这意味着它工作正常,但是当我检查 SQL Server 时, myTable 没有被删除。如果我在 SQL Server Management Studio 中运行相同的语句, MyTable 被删除...

我哪里错了?

请您参考如下方法:

在回答你的问题之前,一些评论:

  • 避免使用查询文本对此类操作进行编码,否则您很可能会遇到安全问题。最好创建 executes table drop 的存储过程:

    create procedure sp_DropTable 
    @tablename varchar(200) 
    as 
    BEGIN 
        DECLARE @SQL VARCHAR(MAX); 
        SET @SQL = 'IF EXISTS(SELECT 1 FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N''' + @tableName + ''') AND type = (N''U'')) DROP TABLE [' + @tableName + ']' 
     
        EXEC (@SQL); 
       END 
    GO 
    

然后将存储过程的名称作为参数传递给您的函数。现在回到你的错误。

表下降不是 transaction ,但您尝试在事务模式中执行它。这使它失败。尝试:

public bool ExecuteQuery(String pQuery) 
{ 
    SqlConnection con = new SqlConnection("MyConnectionString"); 
    con.Open(); 
 
    try 
    { 
        SqlCommand cmd = new SqlCommand(pQuery, con); 
 
        // if you pass just query text 
        cmd.CommandType = CommandType.Text; 
 
        // if you pass stored procedure name 
        // cmd.CommandType = CommandType.StoredProcedure;    
 
        cmd.ExecuteNonQuery(); 
 
        con.Close(); 
 
        return true; 
    } 
    catch (Exception exp) 
    { 
        con.Close(); 
        MessageBox.Show(exp.Message, "Error!!", MessageBoxButtons.OK, MessageBoxIcon.Error); 
    } 
 
    return false; 
}