C# 查询一个值方法ExecuteScalar()
2012-10-17 21:33
113 查看
需要从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#编程时候,有的时候我们需要判断一个字符串是否是数字字符串,我们可以通过以下两种方法来实现。 【方法一】:使用 try{} catch{} 语句。 我们可以在try语句块中试图
- 一个验证IP范围内权限的C#方法,支持 ? * -
- 一个简单方法完成C#时间间隔的计算
- 一个验证IP范围内权限的C#方法,支持 ? * -
- C#中保存GIF文件后透明背景问题的一个解决方法
- 一个简单方法完成C#时间间隔的计算
- 把C#中的静态方法注册进Lua的一个全局方法
- C#启动一个外部程序(方法1) - WinExec
- C# 一个简单分词程序的思路和代码(四) 键树 查询记录
- 一个简单方法完成C#时间间隔的计算
- C# 抽象类其中创建一个静态方法
- 腾讯云图片鉴黄集成到C# SQL Server 怎么在分页获取数据的同时获取到总记录数 sqlserver 操作数据表语句模板 .NET MVC后台发送post请求 百度api查询多个地址的经纬度的问题 try{}里有一个 return 语句,那么紧跟在这个 try 后的 finally {}里的 code 会 不会被执行,什么时候被执行,在 return 前还是后? js获取某个日期