C# 从 SQL Server 数据库中获取数据到标签中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9852454/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get data from SQL Server database into label
提问by Andre C
In my ASP.Net webpage, I have a label and need the label's text to be retrieved from my database.
在我的 ASP.Net 网页中,我有一个标签,需要从我的数据库中检索标签的文本。
I have no problem writing to my database, but it seems trying to retieve the data again is a mission...
我写入数据库没有问题,但似乎再次尝试检索数据是一项任务......
What I need is to get the data from the Pricecolumn in my database, from the table Tickets, from the record where the ConcertNamedata is the same as my webpage's title, or a string associated with my webpage.
我需要的是从Price我的数据库中的列、表Tickets、ConcertName数据与我的网页标题相同的记录或与我的网页相关联的字符串中获取数据。
I have tried many tutorials already, but all just throw me errors, so I decided to try one last place before I just give in and make my labels static.
我已经尝试了很多教程,但所有教程都给我带来了错误,所以我决定在我放弃并使我的标签静态之前尝试最后一个地方。
In case it helps, I have tried the following:
如果有帮助,我尝试了以下方法:
采纳答案by PraveenVenu
Hopes you use c#
希望你使用 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();
回答by Coltech
回答by NuNn DaDdY
Here is an example protecting against SQL Injection and implicity disposes the SqlConnection object with the "using" statement.
这是一个防止 SQL 注入的示例,并使用“using”语句隐式处理 SqlConnection 对象。
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();
}
}
If you're interested in researching ADO .Net a bit more, here is a link to the MSDN documentation for ADO .Net with framework 4.0
如果您有兴趣进一步研究 ADO .Net,这里是 ADO .Net with framework 4.0 的 MSDN 文档的链接
http://msdn.microsoft.com/en-us/library/h43ks021(v=vs.100).aspx
http://msdn.microsoft.com/en-us/library/h43ks021(v=vs.100).aspx

