C# 2005 数据库访问(七)

上一篇介绍了如何查看SQL命令,接着上一篇这一篇我们介绍如何直接执行SQL命令。

       如果程序需要执行面向集合的操作,比如删除、更新所有的满足某一条件的行,则直接使用单一的SQL命令要比使用在C#代码中扩展的SQL命令要更有效,尤其对于大型标来说更是如此。ADO.NET提供SqlCommand和OleCommand对象,以执行SQL命令。这些对象提供Execute()方法执行SQL命令。前面介绍DataReader对象时已经使用ExecuteReader()方法。下面介绍其他的Execute()方法:

      1.SqlCommand的ExecuteScalar方法执行查询:此方法用于执行仅仅返回一个标量的SQL命令(标量即单一值,相对于ExecuteReader()所返回的多行)。下面程序获取表的行数:

using System;
using System.Data;
using System.Data.SqlClient;

class DataExcuteScalarExample
{
    public static void Main()
    {
        SqlConnection thisConnection = new SqlConnection(@"Data Source=(local);User Id=sa;Password=sa;Integrated Security=SSPI;Initial Catalog=northwind");
        thisConnection.Open();

        SqlCommand thisCommand = thisConnection.CreateCommand();
        thisCommand.CommandText = "SELECT COUNT(*) FROM Customers";
        Object countResult = thisCommand.ExecuteScalar();

        Console.WriteLine("Count of Customers={0}",countResult);
        thisConnection.Close;
    }

}

       2.SqlCommand的ExecuteNonQuery方法执行根本就不返回任何数据的命令。如Insert、Update、Delete的数据修改操作不返回任何数据,只返回受影响的行数。下面程序为将一个供应商的产品价格上涨5%。

using System;
using System.Data;
using System.Data.SqlClient;

class DataSqlNonQueryExample
{
    public static void Main()
    {
        SqlConnection thisConnection = new SqlConnection(@"Data Source=(local);User Id=sa;Password=sa;Integrated Security=SSPI;Initial Catalog=northwind");
        thisConnection.Open();

        SqlCommand thisCommand = thisConnection.CreateCommand();
        thisCommand.CommandText = "Update Products Set UnitPrice=UnitPrice*1.05 Where SupplierId=12";

        int rowsAffected = thisCommand.ExecuteNonQurey();

        Console.WriteLine("Rows Update={0}", rowsAffected);
        thisConnection.Close;
    }

}

<注:>本文参考文献

《C#入门经典》清华大学出版社

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值