我嘗試加載我的網頁時遇到此錯誤。任何人都可以建議是什麼原因導致這種情況發生和補救?用戶代碼未處理的sqlexception
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
這是C#代碼
string conStr = ConfigurationManager.ConnectionStrings["MSSQLConnectionString"].ConnectionString;
SqlConnection connection = new SqlConnection(conStr);
string strSqlCmd;
string strSqlCmd2;
strSqlCmd = "INSERT INTO User " + "(UserName, UserPwd, email, address, mobileNo, firstname, lastname, dateofBirth, NRIC, gender)";
strSqlCmd += " VALUES (@Username, @Userpwd, @email, @address, @mobileNo, @firstName, @lastName, @DateOfBirth, @nric, @gender)";
strSqlCmd2 = "INSERT INTO Patient " + "(Allergies, Childhoodillness)";
strSqlCmd2 += "VALUES(@allergies, @Childhood_illness)";
//create command and assign the query and connection from the constructor
SqlCommand cmd = new SqlCommand(strSqlCmd, connection);
SqlCommand cmd2 = new SqlCommand(strSqlCmd2, connection);
cmd.Parameters.AddWithValue("@Username", UserName.Text);
cmd.Parameters.AddWithValue("@Userpwd", Password.Text);
cmd.Parameters.AddWithValue("@email", Email.Text);
cmd.Parameters.AddWithValue("@address", Address.Text);
cmd.Parameters.AddWithValue("@mobileNo", MobileNo.Text);
cmd.Parameters.AddWithValue("@firstName", Password.Text);
cmd.Parameters.AddWithValue("@lastName", Password.Text);
cmd.Parameters.AddWithValue("@DateOfBirth", DOB.Text);
cmd.Parameters.AddWithValue("@nric", NRIC.Text);
cmd.Parameters.AddWithValue("@gender", Gender.Text);
cmd2.Parameters.AddWithValue("@allergies", Allergies.Text);
cmd2.Parameters.AddWithValue("@Childhood_illness", ChildhoodIllness.Text);
connection.Open();
cmd.ExecuteNonQuery();
cmd2.ExecuteNonQuery();
connection.Close();
這是web.config
代碼
<add name="MSSQLConnectionString"
connectionString="Server=localhost; Database= App_Data\PMS.mdf ; Integrated Security=True"
providerName="System.Data.SqlClient" />
「服務器未找到或無法訪問」似乎很明顯。 – 2014-10-10 20:20:57
嘗試在這篇文章中建議的步驟,它可能有所幫助:http://ricardodsanchez.com/2012/04/05/how-to-configure-sql-express-to-accept-remote-connections/ – 2014-10-10 20:21:20
不確定,但我不認爲你直接引用數據庫文件。至少我從來不必這樣做。也許localhost應該是實際的實例名稱。 – RadioSpace 2014-10-10 20:25:49