我以二进制格式将图像保存到数据库中。我在尝试检索它时遇到错误。错误显示“在应用程序配置中找不到连接名称'ConnectionString',或者连接字符串为空。”这是我的代码,我做错了什么?
//Code for generic handler
<%@ WebHandler Language="C#" Class="Handler" %>
using System;
using System.Web;
using System.Configuration;
using System.Data.SqlClient;
public class Handler : IHttpHandler {
public void ProcessRequest (HttpContext context) {
SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["Data Source=ACER-
PC\\SQLEXPRESS;Initial Catalog=imageDemo;Integrated
Security=True"].ConnectionString;
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "Select ImageName,Image from image" + " where ID =@ID";
cmd.CommandType = System.Data.CommandType.Text;
cmd.Connection = con;
SqlParameter ImageID = new SqlParameter("@ID", System.Data.SqlDbType.Int);
ImageID.Value = context.Request.QueryString["ID"];
cmd.Parameters.Add(ImageID);
con.Open();
SqlDataReader dReader = cmd.ExecuteReader();
dReader.Read();
context.Response.BinaryWrite((byte[])dReader["Image"]);
dReader.Close();
con.Close();
}
//Code for datagrid
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="False" DataKeyNames="ID"
DataSourceID="SqlDataSource1">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID"
InsertVisible="False" ReadOnly="True"
SortExpression="ID" />
<asp:BoundField DataField="ImageName" HeaderText="ImageName"
SortExpression="ImageName" />
<asp:TemplateField HeaderText="Image">
<ItemTemplate>
<asp:Image ID="Image1" runat="server"
ImageUrl='<%# "Handler.ashx?ID=" + Eval("ID")%>'/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT [ID], [ImageName], [Image]
FROM [image]"></asp:SqlDataSource>
答案 0 :(得分:3)
“数据源= ACER-PC \ SQLEXPRESS;初始目录= imageDemo;集成安全性=真”是您的连接字符串。
检查你的web.config,看看你是否有这样的东西:
<connectionStrings>
<add name="myConnection" connectionString="Data Source=ACER-PC\\SQLEXPRESS;Initial Catalog=imageDemo;Integrated Security=True" providerName="System.Data.SqlClient"/>
</connectionStrings>
之后,将您的行更改为
con.ConnectionString = ConfigurationManager.ConnectionStrings["myConnection"].ConnectionString;
答案 1 :(得分:2)
错:
con.ConnectionString = ConfigurationManager.ConnectionStrings [“数据源= ACER-
PC \ SQLEXPRESS;初始目录= imageDemo;集成
。安全=真“强>]的ConnectionString;
应该是......
con.ConnectionString =“Data Source = ACER-PC \ SQLEXPRESS; Initial Catalog = imageDemo; Integrated Security = True”;
或者
con.ConnectionString = ConfigurationManager.ConnectionStrings [“YourConnection”]。ConnectionString;
因此,您需要在app.config或web.config
中添加以下内容<connectionStrings>
<add name="YourConnection" connectionString="Data Source=ACER-PC\\SQLEXPRESS;Initial Catalog=imageDemo;Integrated Security=True" providerName="System.Data.SqlClient"/>