溫馨提示×

C#中操作數(shù)據(jù)庫技術(shù)之ExecuteNonQuery用法

c#
小億
152
2024-01-02 17:41:28
欄目: 編程語言

在C#中,ExecuteNonQuery方法是用于執(zhí)行SQL語句,并返回受影響的行數(shù)的方法。它通常用于執(zhí)行INSERT、UPDATE或DELETE語句,因為這些語句不返回任何結(jié)果集。

以下是ExecuteNonQuery方法的用法示例:

using System;
using System.Data.SqlClient;

class Program
{
    static void Main()
    {
        string connectionString = "your_connection_string";
        
        // 創(chuàng)建連接對象
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            connection.Open();
            
            // 創(chuàng)建命令對象
            using (SqlCommand command = new SqlCommand("INSERT INTO MyTable (Column1, Column2) VALUES (@Value1, @Value2)", connection))
            {
                // 添加參數(shù)
                command.Parameters.AddWithValue("@Value1", "Value 1");
                command.Parameters.AddWithValue("@Value2", "Value 2");
                
                // 執(zhí)行SQL語句
                int rowsAffected = command.ExecuteNonQuery();
                
                Console.WriteLine("受影響的行數(shù): " + rowsAffected);
            }
        }
    }
}

在上面的示例中,我們首先創(chuàng)建了一個SqlConnection對象,并使用正確的連接字符串初始化它。然后,我們使用Open方法打開連接。

接下來,我們創(chuàng)建了一個SqlCommand對象,并傳入要執(zhí)行的SQL語句和連接對象。我們還添加了兩個參數(shù),@Value1和@Value2,它們分別在SQL語句中的VALUES子句中使用。

最后,我們調(diào)用ExecuteNonQuery方法執(zhí)行SQL語句,并將返回的受影響的行數(shù)存儲在一個變量中。我們可以使用這個值來確定SQL語句是否成功執(zhí)行,并輸出結(jié)果。

請注意,在使用ExecuteNonQuery方法之后,應該使用using語句塊來關(guān)閉數(shù)據(jù)庫連接和命令對象,以便正確釋放資源。

0