c#运用for循环通过id删除‘数据库
时间: 2023-06-29 08:15:29 浏览: 66
假设您要删除的记录 ID 值是从 1 到 10,您可以使用 for 循环来遍历这些 ID 值,然后依次执行删除操作。具体的实现方式如下所示:
```csharp
using System.Data.SqlClient;
// 1. 定义连接字符串
string connectionString = "Data Source=数据库服务器名称;Initial Catalog=数据库名称;User ID=用户名;Password=密码";
// 2. 建立连接
using (SqlConnection connection = new SqlConnection(connectionString))
{
// 3. 打开连接
connection.Open();
// 4. 定义 SQL 语句
string sql = "DELETE FROM 表名 WHERE ID=@id";
// 5. 定义参数
SqlParameter parameter = new SqlParameter("@id", SqlDbType.Int);
// 6. 使用 for 循环遍历要删除的记录 ID 值
for (int i = 1; i <= 10; i++)
{
// 7. 设置参数值
parameter.Value = i;
// 8. 执行 SQL 命令
SqlCommand command = new SqlCommand(sql, connection);
command.Parameters.Add(parameter);
int result = command.ExecuteNonQuery();
}
// 9. 关闭连接
connection.Close();
}
```
上述代码中,通过 for 循环遍历了要删除的记录 ID 值,每次循环时将当前 ID 值设置为参数的值,然后执行 SQL 命令。需要注意的是,在循环内部创建了 `SqlCommand` 对象,并且每次执行完毕后需要关闭连接。