c# sql数据库增删改查
时间: 2023-08-20 08:51:38 浏览: 126
对于C#中的SQL数据库增删改查操作,你可以使用ADO.NET来实现。下面是一些示例代码:
1. 连接数据库:
```csharp
string connectionString = "Data Source=myServerAddress;Initial Catalog=myDatabase;User ID=myUsername;Password=myPassword";
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
```
2. 插入数据:
```csharp
string insertQuery = "INSERT INTO TableName (Column1, Column2) VALUES (@Value1, @Value2)";
SqlCommand command = new SqlCommand(insertQuery, connection);
command.Parameters.AddWithValue("@Value1", value1);
command.Parameters.AddWithValue("@Value2", value2);
command.ExecuteNonQuery();
```
3. 查询数据:
```csharp
string selectQuery = "SELECT * FROM TableName WHERE Condition";
SqlCommand command = new SqlCommand(selectQuery, connection);
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
// 处理查询结果
}
reader.Close();
```
4. 更新数据:
```csharp
string updateQuery = "UPDATE TableName SET Column1 = @Value1 WHERE Condition";
SqlCommand command = new SqlCommand(updateQuery, connection);
command.Parameters.AddWithValue("@Value1", value1);
command.ExecuteNonQuery();
```
5. 删除数据:
```csharp
string deleteQuery = "DELETE FROM TableName WHERE Condition";
SqlCommand command = new SqlCommand(deleteQuery, connection);
command.ExecuteNonQuery();
```
记得在完成操作后关闭数据库连接:
```csharp
connection.Close();
```
请注意,上述代码中的"TableName"和"Condition"需要替换为你实际的表名和条件。另外,使用参数化查询可以帮助防止SQL注入攻击。
阅读全文