通过HTTP处理程序连接到SQL Server Express数据库

本文关键字:SQL Server Express 数据库 连接 HTTP 处理 程序 通过 | 更新日期: 2023-09-27 18:07:51

每次下载文件时,我都试图更新数据库中的表。数据库是"DefaultConnection(WebsiteName)",是在我使用示例网站模板时创建的。它是存储所有注册用户的数据库。我已经把这个表添加到那个数据库了。

CREATE TABLE [dbo].[Download] (
    [filename] NVARCHAR(50) NULL  , 
    [counter] INT NOT NULL DEFAULT 0 , 
);

我创建了一个HTTP处理程序,当我点击下载并在没有SQL连接部分的情况下工作时触发:

<%@ 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 filename=@filename", 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();行抛出一个异常,表示它无法连接:

在建立到SQL Server的连接时发生了与网络相关或特定于实例的错误。未找到服务器或无法访问服务器。验证实例名是否正确,SQL Server是否配置为允许远程连接。(提供程序:Named Pipes提供程序,错误:40 -无法打开到SQL Server的连接).

我的主要问题是,我如何连接到这个默认数据库,以便我可以在下载文件时更新该表中的信息

通过HTTP处理程序连接到SQL Server Express数据库

您的连接字符串中没有附加的db文件名。请从这里获取本地数据库的连接字符串http://msdn.microsoft.com/en-us/library/hh510202.aspx

我终于使用这个连接到它:

conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);