C#中executenonquery使用的方法有哪些

小億
109
2023-07-28 14:40:31
欄目: 編程語言

在C#中,ExecuteNonQuery方法主要用于執(zhí)行添加、刪除、更新等不返回結(jié)果集的SQL語句。下面是一些常見的使用方法:

  1. 使用SqlCommand對(duì)象的ExecuteNonQuery方法:
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);
}
}
  1. 使用OleDbCommand對(duì)象的ExecuteNonQuery方法:
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);
}
}
  1. 使用SQLiteCommand對(duì)象的ExecuteNonQuery方法:
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);
}
}

這些方法中,都是先創(chuàng)建一個(gè)連接對(duì)象,然后創(chuàng)建一個(gè)命令對(duì)象,并將SQL語句和參數(shù)傳遞給命令對(duì)象,最后執(zhí)行ExecuteNonQuery方法來執(zhí)行SQL語句。執(zhí)行成功后,可以通過返回的行數(shù)來獲取受影響的行數(shù)。

0