C# 查询一个值方法ExecuteScalar()
2012-10-17 21:33
183 查看
需要从SQL查询中返回一个值,如表中记录数。可以使用ExecuteScalar()方法,这个方法只返回一个值。如下边控制台应用程序代码所示:
using System.Data;
using System.Data.SqlClient;
namespace ExecuteScalar
{
class Program
{
static void Main(string[] args)
{
SqlConnection thisConnection = new SqlConnection(
@"Data Source=scott;Initial Catalog=northwind;Persist Security Info=True;User ID=sa;Password=sa123");
thisConnection.Open();
SqlCommand thisCommand = thisConnection.CreateCommand();
thisCommand.CommandText = "select count(*) from customers";
//ExecuteScalar:执行只返回一个值的SQL命令。
object countResult = thisCommand.ExecuteScalar();
Console.WriteLine("Count of Customers={0}",countResult);
Console.ReadLine();
thisConnection.Close();
}
}
}
结果为:
Count of Customers=91
using System.Data;
using System.Data.SqlClient;
namespace ExecuteScalar
{
class Program
{
static void Main(string[] args)
{
SqlConnection thisConnection = new SqlConnection(
@"Data Source=scott;Initial Catalog=northwind;Persist Security Info=True;User ID=sa;Password=sa123");
thisConnection.Open();
SqlCommand thisCommand = thisConnection.CreateCommand();
thisCommand.CommandText = "select count(*) from customers";
//ExecuteScalar:执行只返回一个值的SQL命令。
object countResult = thisCommand.ExecuteScalar();
Console.WriteLine("Count of Customers={0}",countResult);
Console.ReadLine();
thisConnection.Close();
}
}
}
结果为:
Count of Customers=91
相关文章推荐
- C# 查询一个值方法ExecuteScalar()
- C# 查询一个值方法ExecuteScalar()
- C# 查询一个值方法ExecuteScalar()
- C# 查询一个值方法ExecuteScalar()
- C# 查询一个值方法ExecuteScalar()
- 【C#】对异步请求处理程序IHttpAsyncHandler的理解和分享一个易用性封装 【手记】走近科学之为什么明明实现了IEnumerable<T>的类型却不能调用LINQ扩展方法 【手记】手机网页弹出层后屏蔽底层的滑动响应 【手记】ASP.NET提示“未能创建类型”处理 【Web】一个非常简单的移动web消息框 【手记】解决EXCEL跑SQL遇“查询无法运行或数据库表无法打开...”
- c#连接access2003操作必须使用一个可更新的查询解决方法
- C#使用oledb连接excel运行Insert Into语句出现“操作必须使用一个可更新的查询”的解决的方法
- 收藏的一个关于C# ToString的方法集合
- 在进行C#编程时候,有的时候我们需要判断一个字符串是否是数字字符串,我们可以通过以下两种方法来实现。 【方法一】:使用 try{} catch{} 语句。 我们可以在try语句块中试图
- C# 委托:把方法组合到一个数组中使用
- 一个验证IP范围内权限的C#方法,支持 ? * -
- 一个简单方法完成C#时间间隔的计算
- 一个验证IP范围内权限的C#方法,支持 ? * -
- C#中保存GIF文件后透明背景问题的一个解决方法
- 一个简单方法完成C#时间间隔的计算
- 把C#中的静态方法注册进Lua的一个全局方法
- C#写一个查询并插入Oracle
- C#启动一个外部程序(方法1) - WinExec
- C# 一个简单分词程序的思路和代码(四) 键树 查询记录