CSharp中SqlCommand类各函数写出示例代码并解释每个参数
时间: 2024-05-08 12:20:12 浏览: 9
好的,我可以帮你解答。下面是SqlCommand类的几个常用方法以及代码示例和参数解释:
1. ExecuteNonQuery() :执行 SQL 命令并返回受影响的行数。
代码示例:
```
string connectionString = "your_connection_string";
string sqlQuery = "INSERT INTO Customers (CustomerName) VALUES ('test')";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(sqlQuery, connection);
connection.Open();
int rowsAffected = command.ExecuteNonQuery();
Console.WriteLine(rowsAffected + " rows have been affected.");
}
```
解释:在以上代码中,我们向名为 Customers 的表中插入一条记录,该记录包含 'test' 值。ExecuteNonQuery() 方法执行 SQL 命令并返回插入的记录数,最后输出插入的行数(如果有)。
2. ExecuteReader() :执行 SQL 命令并返回一个 SqlDataReader 对象。
代码示例:
```
string connectionString = "your_connection_string";
string sqlQuery = "SELECT CustomerName FROM Customers";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(sqlQuery, connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(reader.GetString(0));
}
}
```
解释:在以上代码中,我们执行了一个 SELECT 查询并返回了一个 SqlDataReader 对象。它可以用来遍历查询结果,最终输出每个记录的 CustomerName 字段的值。
3. ExecuteScalar() :执行 SQL 命令并返回结果集中第一行的第一列。
代码示例:
```
string connectionString = "your_connection_string";
string sqlQuery = "SELECT COUNT(CustomerID) FROM Customers";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(sqlQuery, connection);
connection.Open();
int count = (int)command.ExecuteScalar();
Console.WriteLine("There are " + count + " records in the Customers table.");
}
```
解释:在以上代码中,我们执行了一个 SELECT COUNT 查询,返回了唯一的结果值:Customers 表中的记录数。ExecuteScalar() 方法执行 SQL 命令并返回结果集中第一行的第一列。由于我们查询了一个单一的值,因此我们将结果转换为 int 类型并输出。