System.Data.SqlClient.SqlException:无法打开登录请求的数据库“数据库”。登录失败

时间:2015-08-20 07:13:55

标签: c# html database

我正在尝试访问sql数据库。我在VS2013中创建了C#。但我一直收到这个错误

  

'无法打开登录请求的数据库“数据库”。登录   失败'。

我正在尝试使用IIS管理器从localhost运行它。我是否指向web配置中的connectionstring的数据源错误?我的mdf和日志文件可能在错误的地方?我创建了mdf和日志文件,并将它们放在我的app_data文件夹中。

       //objects we will need to work with the db
        SqlConnection conn;
        SqlCommand cmd;

        //IF PAGE IS NOT A POSTBACK, ADD A HIT
        if (!Page.IsPostBack)
        {
            //connect to the db
            //conn = new SqlConnection(@"Data Source");
            conn = new  
               SqlConnection(WebConfigurationManager.ConnectionStrings
               ["ConnectionString"].ConnectionString);

            //the sql command to increment hits by 1
            cmd = new SqlCommand("UPDATE Hits SET Hits = Hits+1 WHERE 
            Name=@Name", conn);
            cmd.CommandType = CommandType.Text;

            //update where Name is 'Default' which corresponds to this page
            cmd.Parameters.AddWithValue("@Name", "WebForm1");

            using (conn)
            {
                //open the connection
                conn.Open();
                //send the query
                cmd.ExecuteNonQuery();
            }
        }


        //DISPLAY HITS IN OUR LABEL
        //connect to the db
        conn = new SqlConnection(WebConfigurationManager.
                ConnectionStrings["ConnectionString"].
                 ConnectionString);

        //the sql command to select the row of hits corresponding to this           
        page

        cmd = new SqlCommand("SELECT * FROM Hits WHERE Name=@Name", conn);
        cmd.CommandType = CommandType.Text;

        //select where Name is 'Default' which corresponds to this page
        cmd.Parameters.AddWithValue("@Name", "WebForm1");

        using (conn)
        {
            //open the connection
            conn.Open();
            //send the query and store the results in a sqldatareader
            SqlDataReader rdr = cmd.ExecuteReader();

            if (rdr.Read())
            {
                //set the text of our label to the current # of hits
                lblHits.Text = "Default Page Hits - " +  
                rdr["Hits"].ToString();
            }
        }

我在web.config中的连接字符串

<configuration>

   <system.web>
       <compilation debug="true" targetFramework="4.0" />
   </system.web>

  <connectionStrings>
     <add name="ConnectionString" connectionString="Data Source=            
     (local)\SQLEXPRESS; Initial Catalog=Database; Integrated Security=True" 
     providerName="System.Data.SqlClient"/>
  </connectionStrings>

</configuration>

2 个答案:

答案 0 :(得分:0)

Initial Catalog错了。从连接字符串中删除它或使用正确的目录名称。

您还需要在连接字符串中提供凭据,请尝试

Integrated Security=SSPI

答案 1 :(得分:0)

我只是在连接字符串中有一个拼写错误,并且在更正它后我的目标是我的旧 sql-server。

相关问题