2012-03-24 92 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