只有一段代码应该运行在一组SQL Server数据上。这个想法是它读入调整一个jpeg文件并将其写回。它在单行上运行良好。但是,当运行大量数据时,随后的行由于超时而更新命令失败。不是在所有的行上,但它跳过了大多数。SqlConnection和SqlCommand超时
using System.Drawing.Imaging;
using System.IO;
namespace MesResizer
{
class Program
{
static void Main(string[] args)
{
var con = ConfigurationManager.ConnectionStrings["SQLconnString"].ToString();
SqlConnection myConnection = new SqlConnection(con);
GetRows(myConnection);
myConnection.Close();
}
private static void GetRows(SqlConnection connection)
{
Boolean changed = false;
using (connection)
{
SqlCommand command = new SqlCommand("SELECT TOP(16000) strIIImage, intIIID FROM InspectionItem;", connection);
try
{
Writeout("Setting up Database connection..");
connection.Open();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.ReadLine();
return;
}
Writeout("DONE");
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
using (MemoryStream ms = new MemoryStream())
{
int RowId = (int)reader.GetValue(reader.GetOrdinal("intIIID"));
Stream str;
changed = false;
try
{
str = reader.GetStream(reader.GetOrdinal("strIIImage"));
Image imgstr = Image.FromStream(str);
imgstr.Save("before.jpg", ImageFormat.Jpeg);
if (str.Length > 0)
changed = ScaleImage(Image.FromStream(str), ms);
}
catch (ArgumentException e)
{
Writeout("Stream does not have a valid image format or is Null... Unable to process image... " + RowId);
Writeout("Exception: " + e.Message);
}
if (changed)
WriteImage(ms, RowId);
else
Writeout("Image already resized: " + RowId);
}
}
}
else
{
Writeout("No rows found.");
Console.ReadLine();
}
reader.Close();
Console.ReadLine();
}
}
private static void WriteImage(MemoryStream ms, int RowId)
{
var conf = ConfigurationManager.ConnectionStrings["SQLconnString"].ToString();
SqlConnection writecon = new SqlConnection(conf);
writecon.Open();
using (FileStream file = new FileStream("after.jpg", FileMode.Create, System.IO.FileAccess.Write))
{
file.Write(ms.ToArray(), 0, (int)ms.Length);
}
using (SqlCommand cmd = new SqlCommand("UPDATE InspectionItem SET strIIImage = @Image WHERE intIIID = @Id", writecon))
{
cmd.Parameters.Add("@Image", SqlDbType.VarBinary, (int)ms.Length).Value = ms.ToArray();
cmd.Parameters.Add("@Id", SqlDbType.Int).Value = RowId;
cmd.CommandTimeout = 5;
try
{ //This is where it breaks. :)
cmd.ExecuteNonQuery();
}
catch (SqlException e)
{
Writeout(e.Message + "Error occured on row: " + RowId);
return;
}
}
Writeout("Succesfully Resized File: " + RowId);
writecon.Close();
}
}
}
还有就是多余的东西会在这里,因为我一直在试图验证存储实际上是被调整大小和图像一点点其他的东西一样,是有问题的特定行。
我已经评论了发生超时的代码。 :)
任何信息或方向将不胜感激。
TIA。
编辑 在测试数据库上扫描了许多图像格式和行数超过5000+,根本没有任何问题。 我可以看到数据是一张图片的数据,因为我正在将每张图片写入磁盘,但似乎并不想一直写回数据库。非常奇怪
编辑 只要有人想知道这个决议。
最后得出结论:SQLdatareader在数据库上锁定了行。
我现在从数据库中选择数据块,将它们移动到数据表中,关闭数据记录器,并在需要时调整大小并写回。我相信关键是关闭SqlDatareader并释放任何锁。
这是很多代码。请只粘贴相关部分 – Alex
当然不适应更新它..不想离开任何不相关的东西。 –