【发布时间】:2015-09-30 00:45:24
【问题描述】:
我正在尝试使用以下代码从数据库中检索数据:
public partial class populate : System.Web.UI.Page
{
SqlConnection scon = new SqlConnection("Data Source = localhost; Integrated Security = true; Initial Catalog = populate");
protected void Page_Load(object sender, EventArgs e) {
StringBuilder htmlString = new StringBuilder();
if(!IsPostBack)
{
using (SqlCommand scmd = new SqlCommand())
{
scmd.Connection = scon;
scmd.CommandType = CommandType.Text;
scmd.CommandText = "SELECT * FROM populate";
scon.Open();
SqlDataReader articleReader = scmd.ExecuteReader();
htmlString.Append("'Populate page:'");
if (articleReader.HasRows)
{
while (articleReader.Read())
{
htmlString.Append(articleReader["dateTime"]);
htmlString.Append(articleReader["firstName"]);
htmlString.Append(articleReader["lastName"]);
htmlString.Append(articleReader["address"]);
htmlString.Append(articleReader["details"]);
}
populatePlaceHolder.Controls.Add(new Literal { Text = htmlString.ToString() });
articleReader.Close();
articleReader.Dispose();
}
}
}
}
}
它抛出一个错误:
系统找不到指定的文件
我想知道是否有人可以告诉我错误在哪里或指导我完成调试。提前致谢。
(更新):更具体地说,scon.Open() 导致错误:
消息=在建立与 SQL Server 的连接时发生与网络相关或特定于实例的错误。服务器未找到或无法访问。验证实例名称是否正确以及 SQL Server 是否配置为允许远程连接。 (提供者:命名管道提供者,错误:40 - 无法打开与 SQL Server 的连接)
这看起来很容易修复,但我对数据库不是很好。任何帮助将不胜感激。
【问题讨论】:
-
数据库是否与您的表同名,填充?我觉得有点奇怪。
-
@Christos:我知道这很奇怪,但它是一样的:populate.mdf 并且该表也称为“populate”。
-
在哪里(在哪一行代码)会引发该错误?
-
@marc_s:看起来像 scon.Open():这是错误的一部分;消息=建立与 SQL Server 的连接时发生与网络相关或特定于实例的错误。服务器未找到或无法访问。验证实例名称是否正确以及 SQL Server 是否配置为允许远程连接。 (提供者:命名管道提供者,错误:40 - 无法打开与 SQL Server 的连接)
-
所以这可能意味着您的连接字符串是错误的 - SQL Server 实例名称很可能是错误的......
标签: c# html asp.net sql-server