如果你想从一个记录中得到一个值,你可以使用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();
}
}
免责声明:代码直接写入答案窗口,未经测试(我目前无法访问开发环境),因此可能存在错误