C# 查询一个值方法ExecuteScalar()
2012-10-17 21:33
106 查看
需要从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#使用oledb连接excel运行Insert Into语句出现“操作必须使用一个可更新的查询”的解决的方法
- 【C#】对异步请求处理程序IHttpAsyncHandler的理解和分享一个易用性封装 【手记】走近科学之为什么明明实现了IEnumerable<T>的类型却不能调用LINQ扩展方法 【手记】手机网页弹出层后屏蔽底层的滑动响应 【手记】ASP.NET提示“未能创建类型”处理 【Web】一个非常简单的移动web消息框 【手记】解决EXCEL跑SQL遇“查询无法运行或数据库表无法打开...”
- c#连接access2003操作必须使用一个可更新的查询解决方法
- 关于ASP.NET“操作必须使用一个可更新的查询”问题的解决方法
- 一个简单实用的sql数据库查询工具(c#)
- Visual Studio 2005(C#)中只允许一个实例运行的一种方法
- ibatis同一个方法不能查询查询两个表时报错现象
- 一个C#中截取指定长度字符串的方法(含盖半全角问题)
- (JDBC)利用Java反射编写一个万能的数据库表查询方法
- C#一个线程操作另一个线程的控件的方法(转)
- .Net/C#: 一个将在线简体中文网页转为繁体中文页简单方法 (尚不完善 IHttpHandler Proxy / Response.Filter)
- 最近用C#编写了一个在RichTextBox中查找字符串并标记的方法
- C# 设置和获取一个字节的某一位的值的方法 .
- C#中只运行一个实例的方法
- C#2005 一个简单的查询界面代码:DataGridView使用、图像显示、复合查询样例