我认为我需要的很简单,但我无法通过 asp.net 实现它,因为我是一个初学者。
我需要的是像这个例子一样从 sql db 表中显示一个字段到我的网页:
Account Information
Your Name is: <Retrieve it from db>
Your Email is: <Retrieve it from db>
我应该怎么做?
我已经有表成员了。
我需要用 c# 做这个,我使用的是 Visual Studio Web Express 2010
最佳答案
第一步是添加 SQL 客户端命名空间:
using System.Data.SqlClient;
数据库连接
然后我们创建一个 SqlConnection 并指定连接字符串。
SqlConnection myConnection = new SqlConnection("user id=username;" +
"password=password;server=serverurl;" +
"Trusted_Connection=yes;" +
"database=database; " +
"connection timeout=30");
这是连接的最后一部分,由以下简单地执行(记住首先要确保你的连接有一个连接字符串):
try
{
myConnection.Open();
}
catch(Exception e)
{
Console.WriteLine(e.ToString());
}
SQLCommand
一个SqlCommand 至少需要两个东西来操作。命令字符串和连接。指定连接的方式有两种,如下图所示:
SqlCommand myCommand = new SqlCommand("Command String", myConnection);
// - or -
myCommand.Connection = myConnection;
也可以使用 SqlCommand.CommandText 属性以两种方式指定连接字符串。现在让我们看看我们的第一个 SqlCommand。为简单起见,这将是一个简单的 INSERT 命令。
SqlCommand myCommand= new SqlCommand("INSERT INTO table (Column1, Column2) " +
"Values ('string', 1)", myConnection);
// - or -
myCommand.CommandText = "INSERT INTO table (Column1, Column2) " +
"Values ('string', 1)";
SqlDataReader
您不仅需要数据读取器,还需要 SqlCommand。下面的代码演示了如何设置和执行一个简单的阅读器:
try
{
SqlDataReader myReader = null;
SqlCommand myCommand = new SqlCommand("select * from table",
myConnection);
myReader = myCommand.ExecuteReader();
while(myReader.Read())
{
Console.WriteLine(myReader["Column1"].ToString());
Console.WriteLine(myReader["Column2"].ToString());
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
关于c# - 显示从sql db到asp.net网页的信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4417609/