executenonquery

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

小亿
110
2023-07-28 14:40:31
栏目: 编程语言

在C#中,ExecuteNonQuery方法主要用于执行添加、删除、更新等不返回结果集的SQL语句。下面是一些常见的使用方法:

  1. 使用SqlCommand对象的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对象的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对象的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);
}
}

这些方法中,都是先创建一个连接对象,然后创建一个命令对象,并将SQL语句和参数传递给命令对象,最后执行ExecuteNonQuery方法来执行SQL语句。执行成功后,可以通过返回的行数来获取受影响的行数。

0
看了该问题的人还看了