第一步就是添加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