How to use the ExecuteNonQuery method in C# database access technology?
The ExecuteNonQuery method is used to execute SQL statements that do not return any results, such as for inserting, updating, or deleting operations. The steps for using it are as follows:
- Create a SqlConnection object to connect to the database.
using (SqlConnection connection = new SqlConnection(connectionString))
{
// 其中connectionString是连接字符串,用于指定连接的数据库和其他参数
// connectionString的具体内容根据数据库类型和配置而定
connection.Open();
// 打开数据库连接
}
- Create a SqlCommand object to execute the SQL statement.
using (SqlCommand command = new SqlCommand(sql, connection))
{
// 其中sql是要执行的SQL语句,connection是之前创建的SqlConnection对象
// 设置参数(如果有)
command.Parameters.AddWithValue("@param1", value1);
command.Parameters.AddWithValue("@param2", value2);
// 执行SQL语句并返回受影响的行数
int rowsAffected = command.ExecuteNonQuery();
// 可以根据返回值进行相应的处理
}
Note: Before executing the SQL statement, you can use the Parameters property to add parameters in order to prevent SQL injection attacks.
- Close the database connection.
connection.Close();
The complete example code is as follows:
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string sql = "INSERT INTO MyTable (Column1, Column2) VALUES (@param1, @param2)";
using (SqlCommand command = new SqlCommand(sql, connection))
{
command.Parameters.AddWithValue("@param1", value1);
command.Parameters.AddWithValue("@param2", value2);
int rowsAffected = command.ExecuteNonQuery();
// 可以根据返回值进行相应的处理
}
connection.Close();
}
connectionString specifies the type, location, authentication method and other information of the database; sql is the SQL statement to be executed; @param1, @param2 are parameters in the SQL statement used to pass values to the SQL statement; value1, value2 are the specific parameter values.