c# 操作sqlserver 增删改查
时间: 2023-09-14 18:04:56 浏览: 105
c# SQLserver增删改查
以下是使用 C# 操作 SQL Server 的增删改查示例:
1. 连接数据库
```csharp
using System.Data.SqlClient;
string connectionString = "Data Source=(local);Initial Catalog=databaseName;Integrated Security=True";
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
```
2. 插入数据
```csharp
string insertQuery = "INSERT INTO tableName (column1, column2, column3) VALUES (@value1, @value2, @value3)";
SqlCommand command = new SqlCommand(insertQuery, connection);
command.Parameters.AddWithValue("@value1", "value1");
command.Parameters.AddWithValue("@value2", "value2");
command.Parameters.AddWithValue("@value3", "value3");
command.ExecuteNonQuery();
```
3. 查询数据
```csharp
string selectQuery = "SELECT * FROM tableName";
SqlCommand command = new SqlCommand(selectQuery, connection);
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
string column1Value = reader.GetString(0);
string column2Value = reader.GetString(1);
string column3Value = reader.GetString(2);
// 输出或处理查询结果
}
```
4. 更新数据
```csharp
string updateQuery = "UPDATE tableName SET column1 = @value1 WHERE column2 = @value2";
SqlCommand command = new SqlCommand(updateQuery, connection);
command.Parameters.AddWithValue("@value1", "newValue1");
command.Parameters.AddWithValue("@value2", "value2");
command.ExecuteNonQuery();
```
5. 删除数据
```csharp
string deleteQuery = "DELETE FROM tableName WHERE column2 = @value2";
SqlCommand command = new SqlCommand(deleteQuery, connection);
command.Parameters.AddWithValue("@value2", "value2");
command.ExecuteNonQuery();
```
6. 关闭连接
```csharp
connection.Close();
```
阅读全文