C# 图像显示,保存在SQL Server中
我正在尝试显示保存在SQL Server数据库中的图像 这是我正在使用的代码C# 图像显示,保存在SQL Server中,c#,asp.net,sql-server,C#,Asp.net,Sql Server,我正在尝试显示保存在SQL Server数据库中的图像 这是我正在使用的代码 public partial class SavedFileDisplay : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { string strQuery = "select Name, ContentType, Data from tblFiles where id = @id"
public partial class SavedFileDisplay : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string strQuery = "select Name, ContentType, Data from tblFiles where id = @id";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.Add("@id", SqlDbType.Int).Value = Convert.ToInt32(Request.QueryString["ImageID"]);
DataTable dt = GetData(cmd);
if (dt != null)
{
Byte[] bytes = (Byte[])dt.Rows[0]["Data"];
Response.Buffer = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = dt.Rows[0]["ContentType"].ToString();
Response.AddHeader("content-disposition", "attachment;filename=" + dt.Rows[0]["Name"].ToString());
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
}
}
private Boolean GetData(SqlCommand cmd)
{
String strConnString = System.Configuration.ConfigurationManager
.ConnectionStrings["conString"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
cmd.ExecuteNonQuery();
return true;
}
catch (Exception ex)
{
Response.Write(ex.Message);
return false;
}
finally
{
con.Close();
con.Dispose();
}
}
}
问题是,函数
GetData
正在数据表中保存数据,但函数类型为boolean
。请帮我写正确的代码 您需要一个返回DataTable
而不是bool
private DataTable GetData(SqlCommand cmd)
{
string myConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
using (SqlConnection myConn = new SqlConnection(myConnectionString))
{
cmd.Connection = myConn;
using (SqlDataAdapter myDataAdapter = new SqlDataAdapter(cmd))
{
DataTable dtResult = new DataTable();
myDataAdapter.Fill(dtResult);
return dtResult;
}
}
}
由于
GetData()
返回bool,因此将bool值分配给DataTable(DataTable dt=GetData(cmd);
),而bool无法工作。您需要将GetData的返回值更改为DataTable,并更改GetData的逻辑以从数据库检索数据并将其推入DataTable:
private DataTable GetData(SqlCommand cmd)
{
String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
using(var con = new SqlConnection(strConnString))
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
DataTable dt = new DataTable();
//load data into datatable here
dt.Load(cmd.ExecuteReader());
return dt;
}
}
其中是
cmd.CommandText=“Select*from…”
@fubo:dear我使用了您给定的代码,但显示了错误(使用(SqlDataAdapter myDataAdapter=new SqlDataAdapter(cmd,myConnection)))说有一些无效参数。请帮助。@Mr.Waqas-你说得对,我更新了我的答案-无论如何,我也会将SqlCommand cmd=new-SqlCommand(strQuery)
放入using指令中