C#sql server数据库的增删查改
时间: 2023-08-26 12:06:50 浏览: 112
c# SQLserver增删改查
C# 中操作 SQL Server 数据库的增删查改可以使用 ADO.NET,以下是一些基本的示例:
1. 建立数据库连接:
```
using System.Data.SqlClient;
string connectionString = "Data Source=YOUR_SERVER_NAME;Initial Catalog=YOUR_DATABASE_NAME;Integrated Security=True";
SqlConnection connection = new SqlConnection(connectionString);
```
2. 插入数据:
```
string insertQuery = "INSERT INTO YOUR_TABLE_NAME (column1, column2) VALUES (@value1, @value2)";
SqlCommand command = new SqlCommand(insertQuery, connection);
command.Parameters.AddWithValue("@value1", value1);
command.Parameters.AddWithValue("@value2", value2);
connection.Open();
command.ExecuteNonQuery();
connection.Close();
```
3. 查询数据:
```
string selectQuery = "SELECT * FROM YOUR_TABLE_NAME WHERE column1 = @value";
SqlCommand command = new SqlCommand(selectQuery, connection);
command.Parameters.AddWithValue("@value", value);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
// 获取数据
}
reader.Close();
connection.Close();
```
4. 更新数据:
```
string updateQuery = "UPDATE YOUR_TABLE_NAME SET column1 = @newValue WHERE id = @idValue";
SqlCommand command = new SqlCommand(updateQuery, connection);
command.Parameters.AddWithValue("@newValue", newValue);
command.Parameters.AddWithValue("@idValue", idValue);
connection.Open();
command.ExecuteNonQuery();
connection.Close();
```
5. 删除数据:
```
string deleteQuery = "DELETE FROM YOUR_TABLE_NAME WHERE id = @idValue";
SqlCommand command = new SqlCommand(deleteQuery, connection);
command.Parameters.AddWithValue("@idValue", idValue);
connection.Open();
command.ExecuteNonQuery();
connection.Close();
```
请注意,上述示例中的 YOUR_SERVER_NAME、YOUR_DATABASE_NAME、YOUR_TABLE_NAME、column1 等都需要替换为实际的值。此外,还需要注意数据库连接字符串的安全性和防止 SQL 注入攻击的措施。
阅读全文