2010-12-11 13 views
1

我認爲我需要的很簡單,但我無法通過asp.net實現,因爲我是一個初學者。從sql db顯示信息到asp.net網頁

我需要的是一個顯示來自SQL數據庫表中的字段到我的網頁上這樣的例子:

Account Information 

    Your Name is: <Retrieve it from db> 
    Your Email is: <Retrieve it from db> 

我應該怎樣做呢?

我已經有表格成員。

我需要用C#來做到這一點,我使用Visual Studio的Web快訊2010年

+0

你的問題的標題說,這是一個asp.net網頁,但在你的問題你的狀態,你正在使用C#。你能否澄清你的意思? – 2010-12-11 16:40:29

回答

4

第一步就是添加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()); 
} 
+0

是的,我需要使用SQL服務器,我成功地做了一個插入,但如果我只想發佈歡迎,(數據庫用戶名),我應該做的所有這一切只發佈一個名字! ? – Bader 2010-12-11 16:28:18

+0

是的,你需要遵循這些步驟。別擔心,在執行初始設置並將其連接到數據庫後,它變得很容易。 – 2010-12-11 16:39:15

+0

我理解70%,但我應該如何把column1值放在我的頁面中的「名字」旁邊? – Bader 2010-12-11 16:46:41