第三课 SqlCommand对象(翻译)

来源:互联网 发布:淘宝如何申请延期收货 编辑:程序博客网 时间:2024/05/30 05:15

本文档由李欣蔚(nirvana_li)翻译自http://www.csharp-station.com/,转载请注名出处!
更新日期2006-2-14

Lesson 03: The SqlCommand Object

SqlCommand对象

这节课描述了SqlCommand对象以及如何使用它与数据库交互。下面是本课的目标:

  • 知道什么是command对象
  • 学习如何使用ExecuteReader方法查询数据
  • 学习如何使用ExecuteNonQuery方法插入和删除对象
  • 学习如何使用EXecuteScalar方法返回单一值

介绍

SqlCommand对象允许你指定在数据库上执行的操作的类型。比如,你能够对数据库中的行数据执行selectinsertmodify以及delete命令。SqlCommand对象能被用来支持断开连接数据管理的情况,但是在这节课我们将只单独使用SqlCommand对象。后面关于SqlDataAdapter的课程将解释如何使用断开数据实现应用程序。这节课将同时展示如何从数据库中返回一个单独的值,比如表中记录的数量。

创建SqlCommand对象

与其他C#对象相似,通过new实例声明来实例化SqlCommand对象:

    SqlCommand cmd = new SqlCommand("select CategoryName from Categories", conn);

上面一行是典型的实例化SqlCommand对象的代码。它使用一个string参数来保存你想要执行的命令以及一个关于SqlConnection对象的引用。SqlCommand具有重载形式,这些形式你将在以后的示例中看到。

查询数据

当使用SQLselect命令,会得到一组数据集。为了和SqlCommand对象配合使用,你应该使用ExecuteReader方法,它返回一个SqlDataReader对象。我们将在后面的内容讨论SqlDataReader。下面的例子显示了如何使用SqlCommand对象来得到SqlDataReader对象:

// 1. Instantiate a new command with a query and connection
SqlCommand cmd = new SqlCommand("select CategoryName from Categories", conn);

// 2. Call Execute reader to get query results
SqlDataReader rdr = cmd.ExecuteReader();


在上面的示例中,我们通过传递命令字符串核连接对象到构造函数的方式实体化了SqlCommand对象。然后我们通过SqlCommand对象cmd调用ExecuteReader方法得到了SqlDataReader对象。

这些代码是表1ReadData方法的一部分,我们将在后面集中介绍。


插入数据


要对数据库插入数据,使用SqlCommand对象的ExecuteNonQuery方法。下面的代码显示了如何向数据库表插入数据:

// prepare command string
 string insertString = @"
     insert into Categories
     (CategoryName, Description)
     values ('Miscellaneous', 'Whatever doesn''t fit elsewhere')
";
 
 
// 1. Instantiate a new command with a query and connection
 SqlCommand cmd = new SqlCommand(insertString, conn);
 
 
// 2. Call ExecuteNonQuery to send command
 cmd.ExecuteNonQuery();

 

SqlCommand的实例化过程与以前看到的有一些区别,但是基本一致。在构造函数的第一个字符串参数中是用的是插入字符串变量而不三字符串字面值。该变量在SqlCommand声明之前被声明了。


注意在insertString文本中“doesn’’t”的两个单引号(’’)。这是将它转义为适当的单引号。

 

另外一个需要注意的是我们显式指明了列:CategoryNameDescription。列表中有一个主键名为CategoryID。我们忽略这列因为SQL Server将自动添加此字段。试图对主键比如CategoryID添加值会产生异常。

 

为了执行此命令,我们简单的对SqlCommand实体cmd调用ExecuteNonQuery方法。

 

这段代码是表1InsertData方法的一部分,我们将在后面集中介绍。

更新数据

 

ExecuteNonQuery方法同样用来更新数据。下面的代码显示了如何更新数据:

// prepare command string
 string updateString = @"
     update Categories
     set CategoryName = 'Other'
     where CategoryName = 'Miscellaneous'
";
 
 
// 1. Instantiate a new command with command text only
 SqlCommand cmd = new SqlCommand(updateString);
 
 
// 2. Set the Connection property
 cmd.Connection = conn;
 
 
// 3. Call ExecuteNonQuery to send command
 cmd.ExecuteNonQuery();


再一次,我们将SQL命令赋给字符串变量,但是这次我们使用了不同的SqlCommand构造函数,它只适用了命令。在第2步,将SqlConnection对象conn赋值给SqlCommand对象cmd的连接属性。


这同样能够用上面insert命令中使用两个参数的构造函数实现。它说明了你能够在任何时候改变赋值给命令对象的连接对象。

ExecuteNonQuery方法执行更新命令。

 

这些代码是表1UpdateData方法的一部分。我们将在本课后面集中介绍。


删除数据


你同样能够使用ExecuteNonQuery方法删除数据。下面的例子说明了如何使用EXecuteNonQuery方法删除数据库中的记录。

// prepare command string
 string deleteString = @"
     delete from Categories
     where CategoryName = 'Other'
";
 
 
// 1. Instantiate a new command
 SqlCommand cmd = new SqlCommand();
 
 
// 2. Set the CommandText property
 cmd.CommandText = deleteString;
 
 
// 3. Set the Connection property
 cmd.Connection = conn;
 
 
// 4. Call ExecuteNonQuery to send command
 cmd.ExecuteNonQuery();


这个示例使用了没有参数的SqlCommand构造函数。取而代之的是显式地设置了CommandTextSqlCommand对象的连接属性。

我们同样能够使用SqlCommand构造函数在前面的两个重载形式——用来插入或者更新命令——得到相同的结果。它说明了在任何时候既能够改变命令文本又能够改变连接对象。


ExecuteNonQuery方法调用将命令传递给数据库。

 

这些代码是表1DeleteData方法的一部分。我们将在后面的内容中集中介绍。


得到单一值

 

某些时候你想从数据库中只取一个值,它可能是关于数据集的计数、和、平均值或者其他聚合数值。使用ExecuteReader方法并计算代码中的结果并不是做这些事情的有效方式。最好的选择就是让数据库能够执行并且只返回你所需要的单独的值。下面的示例说明了如何使用ExecuteScalar方法来实现:

// 1. Instantiate a new command
 SqlCommand cmd = new SqlCommand("select count(*) from Categories", conn);
 
 
// 2. Call ExecuteNonQuery to send command
 int count = (int)cmd.ExecuteScalar();

 

SqlComand构造函数中的查询语句要求从Categories表中得到所有所有记录的计数。这些查询将致返回单独的值。在第2步中的ExecuteScalar方法返回这个值。因为ExecuteScalar方法返回类型是object,我们使用转换操作符将它转换为int

这些代码在表GetNumberOfRecords方法的一部分,我们将在后面集中介绍它。


集中介绍

为了简单,我们在前面的小节中展示了一部分代码。它同样对于如何在工程程序中使用是有帮助的。表1显示了在这个例子所使用的所有代码,并通过Main方法中产生格式化的输出。

Listing 1.  SqlConnection Demo

 

using System;
 
using System.Data;
 
using System.Data.SqlClient;
 
 
/// <summary>
 
/// Demonstrates how to work with SqlCommand objects
 
/// </summary>

 class SqlCommandDemo
 
{
     SqlConnection conn;
 
     
public SqlCommandDemo()
     
{
         
// Instantiate the connection
         conn = new SqlConnection(
            
"Data Source=(local);Initial Catalog=Northwind;Integrated Security=SSPI");
     }

 
     
// call methods that demo SqlCommand capabilities
     static void Main()
     
{
         SqlCommandDemo scd 
= new SqlCommandDemo();
 
         Console.WriteLine();
         Console.WriteLine(
"Categories Before Insert");
         Console.WriteLine(
"------------------------");
 
         
// use ExecuteReader method
         scd.ReadData();
 
         
// use ExecuteNonQuery method for Insert
         scd.InsertData();
         Console.WriteLine();
         Console.WriteLine(
"Categories After Insert");
         Console.WriteLine(
"------------------------------");
 
        scd.ReadData();
 
         
// use ExecuteNonQuery method for Update
         scd.UpdateData();
 
         Console.WriteLine();
         Console.WriteLine(
"Categories After Update");
         Console.WriteLine(
"------------------------------");
 
         scd.ReadData();
 
         
// use ExecuteNonQuery method for Delete
         scd.DeleteData();
 
         Console.WriteLine();
         Console.WriteLine(
"Categories After Delete");
         Console.WriteLine(
"------------------------------");
 
         scd.ReadData();
 
         
// use ExecuteScalar method
         int numberOfRecords = scd.GetNumberOfRecords();
 
         Console.WriteLine();
         Console.WriteLine(
"Number of Records: {0}", numberOfRecords);
     }

 
     
/// <summary>
     
/// use ExecuteReader method
     
/// </summary>

     public void ReadData()
     
{
        SqlDataReader rdr 
= null;
 
         
try
         
{
             
// Open the connection
             conn.Open();
 
             
// 1. Instantiate a new command with a query and connection
             SqlCommand cmd = new SqlCommand("select CategoryName from Categories", conn);
 
             
// 2. Call Execute reader to get query results
             rdr = cmd.ExecuteReader();
 
             
// print the CategoryName of each record
             while (rdr.Read())
             
{
                 Console.WriteLine(rdr[
0]);
             }

         }

         
finally
         
{
             
// close the reader
             if (rdr != null)
             
{
                 rdr.Close();
             }

 
             
// Close the connection
             if (conn != null)
             
{
                 conn.Close();
             }

         }

     }

 
     
/// <summary>
     
/// use ExecuteNonQuery method for Insert
     
/// </summary>

     public void InsertData()
     
{
         
try
         
{
             
// Open the connection
             conn.Open();
 
             
// prepare command string
             string insertString = @"
                 insert into Categories
                 (CategoryName, Description)
                 values ('Miscellaneous', 'Whatever doesn''t fit elsewhere')
";
 
             
// 1. Instantiate a new command with a query and connection
             SqlCommand cmd = new SqlCommand(insertString, conn);
 
             
// 2. Call ExecuteNonQuery to send command
             cmd.ExecuteNonQuery();
         }

         
finally
         
{
             
// Close the connection
             if (conn != null)
             
{
                 conn.Close();
             }

         }

     }

 
     
/// <summary>
     
/// use ExecuteNonQuery method for Update
     
/// </summary>

     public void UpdateData()
     
{
         
try
         
{
             
// Open the connection
             conn.Open();
 
             
// prepare command string
             string updateString = @"
                 update Categories
                 set CategoryName = 'Other'
                 where CategoryName = 'Miscellaneous'
";
 
             
// 1. Instantiate a new command with command text only
             SqlCommand cmd = new SqlCommand(updateString);
 
             
// 2. Set the Connection property
             cmd.Connection = conn;
 
             
// 3. Call ExecuteNonQuery to send command
             cmd.ExecuteNonQuery();
        }

         
finally
         
{
             
// Close the connection
             if (conn != null)
             
{
                 conn.Close();
             }

         }

     }

 
     
/// <summary>
     
/// use ExecuteNonQuery method for Delete
     
/// </summary>

     public void DeleteData()
     
{
         
try
         
{
             
// Open the connection
             conn.Open();
 
             
// prepare command string
             string deleteString = @"
                 delete from Categories
                 where CategoryName = 'Other'
";
 
             
// 1. Instantiate a new command
             SqlCommand cmd = new SqlCommand();
 
             
// 2. Set the CommandText property
             cmd.CommandText = deleteString;
 
             
// 3. Set the Connection property
             cmd.Connection = conn;
 
             
// 4. Call ExecuteNonQuery to send command
             cmd.ExecuteNonQuery();
         }

         
finally
         
{
             
// Close the connection
             if (conn != null)
             
{
                 conn.Close();
             }

         }

     }

 
     
/// <summary>
     
/// use ExecuteScalar method
     
/// </summary>
     
/// <returns>number of records</returns>

     public int GetNumberOfRecords()
     
{
         
int count = -1;
 
         
try
         
{
             
// Open the connection
             conn.Open();
 
             
// 1. Instantiate a new command
             SqlCommand cmd = new SqlCommand("select count(*) from Categories", conn);
 
             
// 2. Call ExecuteNonQuery to send command
             count = (int)cmd.ExecuteScalar();
         }

         
finally
         
{
            
// Close the connection
             if (conn != null)
             
{
                 conn.Close();
             }

         }

         
return count;
     }

 }


在表1中,SqlConnection对象在SqlCommandDemo结构中被实体化。这是可以的,因为当CLR垃圾回收器执行的时候对象本身会被清除。重要的是在我们做完了工作之后要关闭连接。此程序在每一个方法中打开在一个try语句块的连接,并且在finally语句块中关闭它。

ReadData方法现实Categories表中的CategoryName列的内容。我们在Main方法中使用它许多次来现实Categorie表的当前状态,它在每一个insertupdatedelete命令之后都会改变。因为这样,它能够在每一个函数被调用之后重用来查看效果。


总结

SqlCommand对象允许你擦许并对数据库传送命令。它含有针对不同的命令而特定的方法。ExecuteReader方法返回SqlDataReader对象来现实查询的结果。对于insertupdate以及delete这些SQL命令,使用ExecuteNonQuery方法。如果你只需要查询的单独聚集值,ExecuteScalar方法是最好的选择。

原创粉丝点击