当它不为null时,在sql server中检索varbinary图像

时间:2013-07-29 07:33:55

标签: c# sql-server sql-server-2008 varbinarymax

我正在尝试从SQL Server 2008数据库中检索存储为varbinary(max)列的图像。当image列不等于NULL时,我从数据库中获取图像。下面是我用来检索图像的代码。帮我看看我的代码,我不知道我做错了什么。谢谢!

protected void Page_Load(object sender, EventArgs e)
{
    string strQuery = "select profilepicture from MemberAccount where nric='"+ Session["nric"] +"' and profilepicture IS NOT NULL";
    SqlCommand cmd = new SqlCommand(strQuery);
    DataTable dt = GetData(cmd);
    if (dt != null)
    {
       download(dt);
    }
}

private DataTable GetData(SqlCommand cmd)
{
    DataTable dt = new DataTable();
    SqlConnection con = new SqlConnection("Data Source = localhost; Initial Catalog = MajorProject; Integrated Security= SSPI");
    SqlDataAdapter sda = new SqlDataAdapter();
    cmd.CommandType = CommandType.Text;
    cmd.Connection = con;

    try
    {
        con.Open();
        sda.SelectCommand = cmd;
        sda.Fill(dt);
        return dt;
    }
    catch
    {
        return null;
    }
    finally
    {
        con.Close();
        sda.Dispose();
        con.Dispose();
    }
}

private void download(DataTable dt)
{
    Byte[] bytes = (Byte[])dt.Rows[0]["profilepicture"];
    Response.Buffer = true;
    Response.Charset = "";
    Response.Cache.SetCacheability(HttpCacheability.NoCache);
    Response.ContentType = "image/jpg";
    Response.BinaryWrite(bytes);
    Response.End();
}

行:

Byte[] bytes = (Byte[])dt.Rows[0]["profilepicture"];

错误:

  

位置0没有行。

1 个答案:

答案 0 :(得分:1)

防御性数据库编程101:您需要 检查 是否获得数据!你无法将任何东西转换成图像...而且你不能盲目地假设你会得到数据。总是检查!

private void download(DataTable dt)
{
    // check if you have any rows at all 
    // no rows -> no data to convert!
    if(dt.Rows.Count <= 0)
       return;

    // check if your row #0 even contains data -> if not, you can't do anything!
    if(data.Rows[0].IsNull("profilepicture"))
       return;

    Byte[] bytes = (Byte[])dt.Rows[0]["profilepicture"];
    Response.Buffer = true;
    Response.Charset = "";
    Response.Cache.SetCacheability(HttpCacheability.NoCache);
    Response.ContentType = "image/jpg";
    Response.BinaryWrite(bytes);
    Response.End();
}