我一直在互联网上寻找一种从sql数据表中显示特定内容的方法。我希望我可以根据Id列值显示Content列。 alt text http://photos-h.ak.fbcdn.net/hphotos-ak-snc3/hs031.snc3/11852_1241994617732_1465331687_655971_2468696_n.jpg
答案 0 :(得分:0)
如果您想从一个记录中只有一个值,则可以使用SqlCommand
类的ExecuteScalar
方法:
string title = null;
using (SqlConnection conn = new SqlConnection("your-connection-string"))
using (SqlCommand cmd = new SqlCommand(
"select ContentTitle from {put table name here} where id = 4", conn))
{
conn.Open();
title = (string)conn.ExecuteScalar();
}
if (!string.IsNullOrEmpty(title))
{
// assign title to suitable asp.net control property
}
如果您希望能够针对各种ID执行此操作,不要只连接新的sql字符串。我将重复一遍:不要只是连接一个新的sql字符串。改为使用参数:
string title = null;
using (SqlConnection conn = new SqlConnection("your-connection-string"))
using (SqlCommand cmd = new SqlCommand(
"select ContentTitle from {put table name here} where id = @id", conn))
{
SqlParameter param = new SqlParameter();
param.ParameterName = "@id";
param.Value = yourIdGoesHere;
cmd.Parameters.Add(param);
conn.Open();
title = (string)conn.ExecuteScalar();
}
if (!string.IsNullOrEmpty(title))
{
// assign title to suitable asp.net control property
}
<强>更新强>
样本aspx页面。首先是一些标记(假设该文件名为example.aspx):
<body>
<form id="Form1" runat="server">
Title: <asp:Label id="_titleLabel"
Text="{no title assigned yet}"
runat="server"/>
</form>
</body>
...并且在代码隐藏中(将被称为example.aspx.cs;为简单起见,我仅包含了Page_Load事件):
protected void Page_Load(object sender, EventArgs e)
{
int id;
try
{
if (int.TryParse(Request.QueryString["id"], out id))
{
_titleLabel.Text = GetContentTitle(id);
}
else
{
_titleLabel.Text = "no id given; cannot look up title";
}
}
catch (Exception ex)
{
// do something with the exception info
}
}
private static string GetContentTitle(int id)
{
using (SqlConnection conn = new SqlConnection("your-connection-string"))
using (SqlCommand cmd = new SqlCommand(
"select ContentTitle from {put table name here} where id = @id", conn))
{
SqlParameter param = new SqlParameter();
param.ParameterName = "@id";
param.Value = yourIdGoesHere;
cmd.Parameters.Add(param);
conn.Open();
return (string)conn.ExecuteScalar();
}
}
免责声明:代码直接写入答案窗口而未经过测试(我现在无法访问开发环境)因此可能存在错误