2012-03-24 149 views
2

在我的ASP.Net網頁中,我有一個標籤,需要從我的數據庫中檢索標籤的文本。從SQL Server數據庫獲取數據到標籤中

我沒有問題,寫我的數據庫,但它似乎在嘗試再次retieve數據是一個使命...

我需要的是讓我的數據庫從Price列中的數據,從表Tickets,其中ConcertName數據與我網頁的標題或與我的網頁相關的字符串相同。

我已經嘗試了很多教程,但都只是拋出錯誤,所以我決定嘗試最後一個地方,然後讓我的標籤靜止。

萬一有幫助,我已經試過如下:

First Try

Second Try

Third Try

Fourth Try

回答

4

的希望您使用C#

string MyPageTitle="MyPageTitle"; // your page title here 
string myConnectionString = "connectionstring"; //you connectionstring goes here 

SqlCommand cmd= new SqlCommand("select Price from Tickets where ConcertName ='" + MyPageTitle.Replace("'","''") + "'" , new SqlConnection(myConnectionString)); 
cmd.Connection.Open(); 
labelPrice.Text= cmd.ExecuteScalar().ToString(); // assign to your label 
cmd.Connection.Close(); 
+0

摸索出我所有的現有代碼是正確的,只需要命令字符串。它的工作,所以謝謝。 – 2012-03-25 10:26:32

1

看起來像要將標籤綁定到數據源。 Here是一個很好的例子。

1

以下是一個防範SQL注入的示例,並且隱含地將SqlConnection對象與「using」語句配置在一起。

string concert = "webpage title or string from webpage"; 

using(SqlConnection conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["connString"].ConnectionString)) 
{ 
    string sqlSelect = @"select price 
         from tickets 
         where concert_name = @searchString"; 
    using(SqlCommand cmd = new SqlCommand(strSelect, conn)) 
    { 
     cmd.Parameters.AddWithValue("@searchString", concert); 
     conn.Open(); 
     priceLabel.Text = cmd.ExecuteScalar().ToString(); 
    } 
} 

如果你有興趣在研究ADO淨多一點,這裏是MSDN文檔的鏈接ADO的.Net框架與4.0

http://msdn.microsoft.com/en-us/library/h43ks021(v=vs.100).aspx

+0

SqlCommand也實現了IDisposable - 爲什麼沒有在using語句中呢? – Bridge 2012-03-25 00:05:02