How to use ExecuteNonQuery in database operations with C#
In C#, the ExecuteNonQuery method is used to execute SQL statements and return the number of rows affected. It is usually used for executing INSERT, UPDATE, or DELETE statements as they do not return any result sets.
Here is an example of how to use the ExecuteNonQuery method:
using System;
using System.Data.SqlClient;
class Program
{
static void Main()
{
string connectionString = "your_connection_string";
// 创建连接对象
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
// 创建命令对象
using (SqlCommand command = new SqlCommand("INSERT INTO MyTable (Column1, Column2) VALUES (@Value1, @Value2)", connection))
{
// 添加参数
command.Parameters.AddWithValue("@Value1", "Value 1");
command.Parameters.AddWithValue("@Value2", "Value 2");
// 执行SQL语句
int rowsAffected = command.ExecuteNonQuery();
Console.WriteLine("受影响的行数: " + rowsAffected);
}
}
}
}
In the example above, we first create a SqlConnection object and initialize it with the correct connection string. Then, we open the connection using the Open method.
Next, we created a SqlCommand object and passed in the SQL statement to be executed and the connection object. Additionally, we added two parameters, @Value1 and @Value2, which are used in the VALUES clause of the SQL statement.
Finally, we use the ExecuteNonQuery method to execute the SQL statement and store the number of affected rows returned in a variable. We can use this value to determine if the SQL statement was successfully executed and output the results.
Please note that after using the ExecuteNonQuery method, you should use a using statement block to close the database connection and command object in order to properly release resources.