c#通过id删除数据库
时间: 2023-08-02 12:19:01 浏览: 63
您可以使用 C# 中的 SQL 语句来删除数据库中的记录。具体的实现方式如下所示:
```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);
parameter.Value = 1; // 这里的 1 是要删除的记录的 ID 值
// 6. 执行 SQL 命令
SqlCommand command = new SqlCommand(sql, connection);
command.Parameters.Add(parameter);
int result = command.ExecuteNonQuery();
// 7. 关闭连接
connection.Close();
}
```
上述代码中,`connectionString` 是数据库连接字符串,`sql` 是要执行的 SQL 语句,`parameter` 是 SQL 语句中的参数,`result` 是执行 SQL 命令后受影响的行数。其中,`@id` 是一个占位符,表示要删除的记录的 ID 值,通过 `SqlParameter` 类型的 `Value` 属性来指定具体的值。