从数据库中删除仅在调试时有效

本文关键字:调试 有效 数据库 删除 | 更新日期: 2023-09-27 18:18:53

我正在从包含BLOB的数据库中读取行。我将这些blobs中的每一个作为文件保存到我的磁盘上。之后,我想删除我刚刚读取的行。现在的问题是:当我调试时,一切都很顺利。当我在没有调试断点的情况下运行时,它不会删除任何东西!而且不会出现错误

我使用c#和MS-SQL服务器。

下面是我的代码:
class Program
{
    static void Main(string[] args)
    {
        if (args[0] == "/?" || args.Length != 1)
        {
            Console.WriteLine("BlobReader");
            Console.WriteLine("Will read blob from database and write is as a file to destination specified in database.");
            Console.WriteLine();
            Console.WriteLine("BlobReader <AppName>");
            Console.WriteLine();
            Console.WriteLine("<AppName>: Application name which identifies which files to extract and save.");
            EndProgram();
        }
        string now = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss.fff");
        Console.WriteLine("writing files to disk");
        bool success = SqlBlob2File(args[0], now);
        if (success)
        {
            Console.WriteLine("Deleting db");
            DeleteRows(args[0], now);
            Console.WriteLine("Db deleted");
        }
        EndProgram();
    }
    static void EndProgram()
    {
        Console.WriteLine();
        Console.WriteLine("Press any key to end.");
        Console.ReadLine();
    }
    static private void DeleteRows(string app, string now)
    {
        try
        {
            string connectionString = ConfigurationManager.ConnectionStrings["dbConn"].ToString();
            SqlConnection connection = new SqlConnection(connectionString);
            string sql = string.Format("DELETE FROM Blobs WHERE Application = '{0}' AND CreatedDate < '{1}'", app,
                                       now);
            SqlCommand cmd = new SqlCommand(sql, connection);
            connection.Open();
            cmd.BeginExecuteNonQuery();
            connection.Close();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
    static private bool SqlBlob2File(string app, string now)
    {
        bool success;

        string connectionString = ConfigurationManager.ConnectionStrings["dbConn"].ToString();
        SqlConnection connection = new SqlConnection(connectionString);
        try
        {
            int blobCol = 0; // the column # of the BLOB field
            string sql =
                string.Format(
                    "SELECT Blob, Drive, Folder, FileName FROM Blobs WHERE Application='{0}' AND CreatedDate < '{1}'",
                    app, now);
            SqlCommand cmd = new SqlCommand(sql, connection);
            connection.Open();
            SqlDataReader dr = cmd.ExecuteReader();
            while (dr.Read())
            {
                string destFilePath = string.Format("{0}{1}{2}", dr["Drive"], dr["Folder"], dr["FileName"]);
                Byte[] b = new Byte[(dr.GetBytes(blobCol, 0, null, 0, int.MaxValue))];
                dr.GetBytes(blobCol, 0, b, 0, b.Length);
                System.IO.FileStream fs = new System.IO.FileStream(destFilePath, System.IO.FileMode.Create,
                                                                   System.IO.FileAccess.Write);
                fs.Write(b, 0, b.Length);
                fs.Close();
                Console.WriteLine("Blob written to file successfully");
            }
            dr.Close();

            success = true;
        }
        catch (SqlException ex)
        {
            success = false;
            Console.WriteLine(ex.Message);
        }
        finally
        {
            connection.Close();
        }
        return success;
    }
}

如果我在DeleteRows方法中设置了一个断点,它就会从数据库中删除。

从数据库中删除仅在调试时有效

如果你使用这个cmd.BeginExecuteNonQuery(),你就必须使用EndExecuteNonquery()

否则,它不会被删除,并可能造成内存泄漏问题。

最好的方法是使用cmd.ExecuteNonQuery();

当您删除Connection.Close时是否也会发生这种情况?由于您正在删除异步,因此可能在操作完成之前关闭连接,而不像当您有断点并且代码执行等待时。

另外,您可能想使用以下方式来代替使用SqlConnection:

using (sqlConnection con = new SqlConnection()) 
{
// your code
 }

这样,当连接超出作用域或出现问题时,连接将自动关闭。

我同意MahaSwetha的观点,即cmd.ExecuteNonQuery()将使您的工作更轻松。此外,cmd.ExecuteNonQuery()返回一个int值,告诉您更改了多少行。有时候可以派上用场