c#对 sql service对多张表进行增删改查
时间: 2023-08-12 19:04:37 浏览: 131
C#对SQLserver增删改查
5星 · 资源好评率100%
要对多张表进行增删改查,需要使用 C# 中的 ADO.NET 技术与 SQL Server 进行交互。以下是一个简单的示例代码:
```csharp
using System;
using System.Data.SqlClient;
class Program
{
static void Main(string[] args)
{
string connectionString = "Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
// 查询操作
string sqlQuery = "SELECT * FROM Table1 INNER JOIN Table2 ON Table1.Id = Table2.Table1Id";
SqlCommand command = new SqlCommand(sqlQuery, connection);
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
// 处理查询结果
Console.WriteLine(reader["Column1"].ToString());
Console.WriteLine(reader["Column2"].ToString());
}
reader.Close();
// 插入操作
string sqlInsert = "INSERT INTO Table1 (Column1, Column2) VALUES ('Value1', 'Value2')";
command = new SqlCommand(sqlInsert, connection);
int rowsAffected = command.ExecuteNonQuery();
Console.WriteLine(rowsAffected + " rows inserted.");
// 更新操作
string sqlUpdate = "UPDATE Table1 SET Column1 = 'NewValue' WHERE Column2 = 'Value2'";
command = new SqlCommand(sqlUpdate, connection);
rowsAffected = command.ExecuteNonQuery();
Console.WriteLine(rowsAffected + " rows updated.");
// 删除操作
string sqlDelete = "DELETE FROM Table2 WHERE Column1 = 'Value'";
command = new SqlCommand(sqlDelete, connection);
rowsAffected = command.ExecuteNonQuery();
Console.WriteLine(rowsAffected + " rows deleted.");
}
}
}
```
在示例代码中,使用了 `SqlConnection` 类建立与 SQL Server 数据库的连接,并使用 `SqlCommand` 类执行 SQL 命令,包括查询、插入、更新和删除操作。需要根据具体的业务需求,编写对应的 SQL 命令。
阅读全文