在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语句。执行成功后,可以通过返回的行数来获取受影响的行数。