c# sql server连接(增、删、改、查)
时间: 2023-04-24 21:00:42 浏览: 311
C#和SQL Server连接可以使用ADO.NET技术实现,以下是增删改查的示例代码:
1. 增加数据:
```
using System.Data.SqlClient;
string connectionString = "Data Source=yourServerName;Initial Catalog=yourDatabaseName;Integrated Security=True";
string insertQuery = "INSERT INTO yourTableName (column1, column2) VALUES (@value1, @value2)";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(insertQuery, connection);
command.Parameters.AddWithValue("@value1", "someValue1");
command.Parameters.AddWithValue("@value2", "someValue2");
connection.Open();
int rowsAffected = command.ExecuteNonQuery();
}
```
2. 删除数据:
```
using System.Data.SqlClient;
string connectionString = "Data Source=yourServerName;Initial Catalog=yourDatabaseName;Integrated Security=True";
string deleteQuery = "DELETE FROM yourTableName WHERE column1 = @value1";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(deleteQuery, connection);
command.Parameters.AddWithValue("@value1", "someValue1");
connection.Open();
int rowsAffected = command.ExecuteNonQuery();
}
```
3. 修改数据:
```
using System.Data.SqlClient;
string connectionString = "Data Source=yourServerName;Initial Catalog=yourDatabaseName;Integrated Security=True";
string updateQuery = "UPDATE yourTableName SET column1 = @value1 WHERE column2 = @value2";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(updateQuery, connection);
command.Parameters.AddWithValue("@value1", "newValue1");
command.Parameters.AddWithValue("@value2", "someValue2");
connection.Open();
int rowsAffected = command.ExecuteNonQuery();
}
```
4. 查询数据:
```
using System.Data.SqlClient;
string connectionString = "Data Source=yourServerName;Initial Catalog=yourDatabaseName;Integrated Security=True";
string selectQuery = "SELECT * FROM yourTableName WHERE column1 = @value1";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(selectQuery, connection);
command.Parameters.AddWithValue("@value1", "someValue1");
connection.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
// do something with the data
}
}
```
阅读全文