在C#中,ExecuteNonQuery方法主要用于執行添加、刪除、更新等不返回結果集的SQL語句。下面是一些常見的使用方法:
string connectionString = "your_connection_string";
string query = "INSERT INTO TableName (column1, column2) VALUES (@value1, @value2)";
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand command = new SqlCommand(query, connection))
{
command.Parameters.AddWithValue("@value1", value1);
command.Parameters.AddWithValue("@value2", value2);
connection.Open();
int rowsAffected = command.ExecuteNonQuery();
connection.Close();
Console.WriteLine("Rows affected: " + rowsAffected);
}
}
string connectionString = "your_connection_string";
string query = "INSERT INTO TableName (column1, column2) VALUES (?, ?)";
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
using (OleDbCommand command = new OleDbCommand(query, connection))
{
command.Parameters.AddWithValue("@value1", value1);
command.Parameters.AddWithValue("@value2", value2);
connection.Open();
int rowsAffected = command.ExecuteNonQuery();
connection.Close();
Console.WriteLine("Rows affected: " + rowsAffected);
}
}
string connectionString = "your_connection_string";
string query = "INSERT INTO TableName (column1, column2) VALUES (@value1, @value2)";
using (SQLiteConnection connection = new SQLiteConnection(connectionString))
{
using (SQLiteCommand command = new SQLiteCommand(query, connection))
{
command.Parameters.AddWithValue("@value1", value1);
command.Parameters.AddWithValue("@value2", value2);
connection.Open();
int rowsAffected = command.ExecuteNonQuery();
connection.Close();
Console.WriteLine("Rows affected: " + rowsAffected);
}
}
這些方法中,都是先創建一個連接對象,然后創建一個命令對象,并將SQL語句和參數傳遞給命令對象,最后執行ExecuteNonQuery方法來執行SQL語句。執行成功后,可以通過返回的行數來獲取受影響的行數。