我正在使用 Visual Web Developer 2010 Express 和 SQL Server 2008 R2 Management Studio Express
大家好,
这里的 C# 相当新。我正在尝试关注this C# ADO.NET 教程(当前在步骤 2 ),我被难住了。我正在遵循所有步骤,其中的所有内容对我来说都有意义,但是每当我尝试调试时,它都不会显示任何内容(从 C# 方法没有将 Northwind 数据库中的表打印到我的网页上的意义上来说) WebApplication1
的 Default.aspx 页面。
有一段时间,我认为这是我的连接字符串 conn
,并且我没有命名 “Data Source”
属性,根据我的理解,它是我尝试连接的服务器的名称。它全部位于本地计算机上,并且我输入了正确的服务器名称..我认为。服务器名称为 AZUES-221\JDOESQLSERVER
我正确地转义了反斜杠,但我仍然不知道。我的编码中是否存在缺陷?请帮忙!
C# 代码
using System;
using System.Data;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
namespace WebApplication1
{
public partial class SqlConnectionDemo : System.Web.UI.Page
{
protected void Main(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=AZUES-221\\JDOESQLSERVER; Initial Catalog=Northwind; Integrated Security=SSPI");
SqlDataReader rdr = null;
try
{
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM Customers", conn); //passed the connection
rdr = cmd.ExecuteReader(); // get query results
while (rdr.Read()) //prints out whatever was
{ Console.WriteLine(rdr[0]); }//selected in the table
}
finally
{
if (rdr != null)// closes
{ rdr.Close(); }// the reader
if (conn != null)//closes
{ conn.Close(); }// the connection
}
}
}
}
提前致谢
最佳答案
由于您的示例似乎是一个 WebProject ,请尝试将代码放入 Page_Load
eventHandler 中。之后,您应该尝试将数据打印到调试
窗口或网页中的控件。
using System;
using System.Data;
// and all the others ...
namespace WebApplication1
{
public partial class SqlConnectionDemo : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=AZUES-221\\JDOESQLSERVER; Initial Catalog=Northwind; Integrated Security=SSPI");
SqlDataReader rdr = null;
try
{
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM Customers", conn);
rdr = cmd.ExecuteReader(); // get query results
while (rdr.Read()) //prints out whatever was
{
System.Diagnostics.Debug.WriteLine(rdr[0]); // or on the other hand
lblOutput.Text += rdr[0]; // as a "quick and dirty" solution!
}
}
finally
{
if (rdr != null)// closes
{ rdr.Close(); }// the reader
if (conn != null)//closes
{ conn.Close(); }// the connection
}
}
}
}
您可能会发现查看databound controls非常有用。或者只是使用其他类型的项目(例如 winForm、控制台...)
关于c# - 为什么C#不显示表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9607537/