Sql Server 返回一个字段的方法

Visual C# 动态操作 SQL Server 数据库实例教程(6):返回一个字段的方法

前面介绍了带参数的SQL语句执行方法带参数的存储过程执行方法等方法,这一篇我们介绍返回一个字段的方法,它调用通用数据访问类(SqlHelper)执行 SqlHelper.ExecuteReader()方法,使用示例为;

object myobj = SqlHelper.ExecuteScalar(conn, CommandType.Text, sql, null);

其中传递的4个参数:

“conn”—为链接字符;

“ CommandType.Text”—表示要执行的SQL命令的类型;

“sql”—要执行的SQL命令语句;

“null”—第四个参数为空。

protected void btnExecuteScalar_Click(object sender, EventArgs e)
{
//获取要执行的命令
string sql = "select top 2 title from menularticle where classID_A=8";
SqlCommand cmd = new SqlCommand();
//定义对象资源保存的范围,一但using范围结束,将释放对方所占资源
using (SqlConnection conn = new SqlConnection(SqlHelper.ConnectionStringLocalTransaction))
{
//打开连接
conn.Open();
//调用执行方法,因为没有参数,所以最后一项直接设置为null
//注意:返回结果是 object类型
object myobj = SqlHelper.ExecuteScalar(conn, CommandType.Text, sql, null);
//显示返回结果
Response.Write(" ");
}
}

要了解更多情况可查看本人网站的相关内容。

posted on 2008-05-22 12:43  tzwhx  阅读(688)  评论(0编辑  收藏  举报

导航