我正在从包含 BLOB 的数据库中读取行。我将这些 blob 中的每一个都作为文件保存到我的磁盘中。之后我想删除我刚刚读过的行。现在的问题是:当我调试时,一切都像魅力一样。当我在没有调试断点的情况下运行时,它不会删除任何东西!它不会出现错误。
我使用 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 中设置断点,它会从数据库中删除。如果我不这样做,则不会删除任何内容。