c#连接sqlserver数据库增删改操作
时间: 2024-10-12 14:17:13 浏览: 29
C#如何实现对sql server数据库的增删改查
在C#中,连接SQL Server数据库并进行增删改操作,通常会使用ADO.NET提供的`SqlConnection`, `SqlCommand`, 和 `SqlDataReader` 等类。下面是一个基本的例子:
```csharp
using System.Data.SqlClient;
// 连接字符串示例
string connectionString = "Data Source=your_server;Initial Catalog=your_database;User ID=your_username;Password=your_password";
try
{
// 创建SqlConnection实例
using (SqlConnection connection = new SqlConnection(connectionString))
{
// 打开连接
connection.Open();
// 插入操作(插入数据)
string insertQuery = "INSERT INTO YourTable (Column1, Column2) VALUES (@Value1, @Value2)";
SqlCommand command = new SqlCommand(insertQuery, connection);
command.Parameters.AddWithValue("@Value1", value1);
command.Parameters.AddWithValue("@Value2", value2);
command.ExecuteNonQuery();
// 更新操作(更新数据)
string updateQuery = "UPDATE YourTable SET Column1 = @NewValue WHERE ColumnID = @Id";
command = new SqlCommand(updateQuery, connection);
command.Parameters.AddWithValue("@NewValue", newValue);
command.Parameters.AddWithValue("@Id", id);
command.ExecuteNonQuery();
// 删除操作(删除数据)
string deleteQuery = "DELETE FROM YourTable WHERE ColumnID = @Id";
command = new SqlCommand(deleteQuery, connection);
command.Parameters.AddWithValue("@Id", targetId);
command.ExecuteNonQuery();
}
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
// 关闭连接
connection.Close();
```
别忘了替换上述代码中的占位符(如`your_server`, `your_database`, `your_username`, `your_password`, `YourTable`, `value1`, `value2`, `newValue`, `id`, `targetId`)为实际的值。
阅读全文