【发布时间】:2013-07-29 07:33:55
【问题描述】:
我正在尝试从我的 SQL Server 2008 数据库中检索存储为 varbinary(max) 列的图像。当图像列不等于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 处没有行。
【问题讨论】:
-
了解如何使用 CommandParameters 以及 Session["nric"] 中的值是什么。?如果您使用该值直接在 SSMS 中执行查询会发生什么?
-
您可以添加额外的保护措施:if (dt != null && dt.Rows != null && dt.Rows.Count>0)
-
有点跑题了,但仍然...... @Rene:如果 dt 不为空,则 dt.Rows 永远不会为空,因为这是在 DataTable 的构造函数中初始化的,所以你可以将您的代码缩短为 (dt != null && dt.Rows.Count > 0)
-
@ManishDalal 这是真的。我没有检查那个实现细节......
标签: c# sql-server sql-server-2008 varbinarymax