1

我尝试从表中加载CODE并用作最终 jpg 的名称...但我不知道如何为每个图像使用他的名称和代码...您有想法吗?NAME_IMAGEIMAGES

SqlConnection connection = new SqlConnection("*****");
connection.Open();
SqlCommand command = new SqlCommand("SELECT IMAGE,NAME_IMAGE,CODE FROM IMAGES", connection);
byte[] buffer = (byte[]) command.ExecuteScalar ();
connection.Close();
FileStream fs = new FileStream(@"C:\Users\L\Desktop\\" + (CODE) + "_" + (NAME_IMAGE) + ".jpg", FileMode.Create);
fs.Write(buffer, 0, buffer.Length);
fs.Close();
4

1 回答 1

2

您正在阅读多列,并且没有where子句,所以这里的第一个问题是ExecuteScalar- 旨在读取第一行的第一列。由于这里不是这种情况,因此您应该ExecuteReader改为查看。或者包装读者的工具,例如“dapper”:

using(var connection = new SqlConnection("*****"))
{
    var data = connection.Query("SELECT IMAGE,NAME_IMAGE,CODE FROM IMAGES");
    foreach(dynamic row in data)
    {
        byte[] data = row.IMAGE; // yes, as simple as that
        string name = row.NAME_IMAGE;
        //... do something with data / name
    }
}

或通过原始 ADO.NET:

using(var connection = new SqlConnection("*****"))
using(var cmd = connection.CreateCommand())
{
    cmd.CommandText = "SELECT IMAGE,NAME_IMAGE,CODE FROM IMAGES";
    connection.Open();
    using(var reader = cmd.ExecuteReader())
    {
        while(reader.Read())
        {
            byte[] data = (byte[])reader["IMAGE"];
            string name = (string)reader["NAME"];
            // ...
        }
    }
}
于 2013-09-09T08:16:57.930 回答