第一步就是添加SQL客户端命名空间:
using System.Data.SqlClient;
DB连接
然后我们创建一个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());
}
你的问题的标题说,这是一个asp.net网页,但在你的问题你的状态,你正在使用C#。你能否澄清你的意思? – 2010-12-11 16:40:29