我試圖在每次下載文件時更新數據庫中的表。數據庫是使用示例網站模板時創建的「DefaultConnection(WebsiteName)」。它是存儲所有註冊用戶的數據庫。我已將此表添加到該數據庫。通過HTTP處理程序連接到SQL Server Express數據庫
CREATE TABLE [dbo].[Download] (
[filename] NVARCHAR(50) NULL ,
[counter] INT NOT NULL DEFAULT 0 ,
);
我創造當我點擊下載的是被解僱,工作沒有SQL連接部分HTTP處理程序:
<%@ WebHandler Language="C#" Class="Download" %>
using System;
using System.Web;
using System.IO;
using System.Data;
using System.Data.SqlClient;
using System.Web.Configuration;
public class Download : IHttpHandler {
SqlConnection conn;
SqlCommand cmd;
private string FilesPath
{
get
{
return @"path to directory holding files";
}
}
public void ProcessRequest(HttpContext context)
{
string fileName = context.Request.QueryString["filename"];
if (!string.IsNullOrEmpty(fileName) && File.Exists(FilesPath + fileName))
{
context.Response.ContentType = "application/octet-stream";
context.Response.AddHeader("Content-Disposition", string.Format("attachment; filename=\"{0}\"", fileName));
context.Response.WriteFile(FilesPath + fileName);
//connect to the db
conn = new SqlConnection(
"Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-websiteName-20130405020152;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-websiteName-20130405020152.mdf");
//the sql command to increment counter by 1
cmd = new SqlCommand("UPDATE counter SET counter = counter+1 WHERE [email protected]", conn);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@filename", "Default");
using (conn)
{
//open the connection
conn.Open();
//send the query
cmd.ExecuteNonQuery();
}
conn.Close();
}
else
{
context.Response.ContentType = "text/plain";
context.Response.Write(FilesPath + fileName + " Invalid filename");
}
}
public bool IsReusable {
get {
return false;
}
}
}
我不能讓它與任何連接字符串我能找到連接。我試過了「web.config」中顯示的那個。它總是會嘗試連接了一段時間,但隨後拋出的conn.Open();
線異常說它無法連接:
A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server) .
我的主要問題是,如何連接到這個默認的數據庫,這樣我可以下載文件時更新此表中的信息。
是什麼錯誤消息說? – usr 2013-04-06 09:06:23
@usr使用連接字符串,我可以通過右鍵單擊 - >屬性:建立與SQL Server的連接時發生網絡相關或實例特定的錯誤。服務器未找到或無法訪問。驗證實例名稱是否正確,並將SQL Server配置爲允許遠程連接。 (提供程序:命名管道提供程序,錯誤:40 - 無法打開與SQL Server的連接) – 2013-04-06 09:17:35