System.Data.SqlClient.SqlException:无法打开数据库";数据库”;登录时请求.登
本文关键字:数据库 quot 登录 请求 SqlException SqlClient Data System | 更新日期: 2023-09-27 18:08:47
我正在尝试访问sql数据库。我在VS2013 C#中创建。但我一直收到这个错误
'无法打开登录请求的数据库"database"。登录失败。'
我正在尝试使用IIS管理器在本地主机上运行此程序。我在web配置中的连接字符串是否指向错误的数据源?我可能把mdf和日志文件放错地方了?我创建了mdf和日志文件,并将它们放在appdata文件夹中。
//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>
Initial Catalog
错误。请将其从连接字符串中删除,或者使用正确的目录名称。
此外,您需要在连接字符串中提供凭据,请尝试
Integrated Security=SSPI
我只是在连接字符串中有一个拼写错误,在纠正它后,我将目标锁定在我的旧sql server上。