C# DataGridView数据保存至数据库的方法

在C#中,DataGridView控件是Windows Forms应用程序中常用的数据展示控件,它可以方便地展示和编辑数据。然而,将DataGridView中的数据保存到数据库是实现数据持久化的关键步骤。以下是将DataGridView数据保存到数据库的几种方法:

### 方法一:使用SqlDataAdapter和SqlCommand

1. **连接数据库**:首先,需要建立与数据库的连接。

2. **创建SqlDataAdapter**:使用SqlDataAdapter来填充DataSet。

3. **创建SqlCommand**:根据需要执行的SQL语句创建SqlCommand。

4. **执行更新**:使用SqlDataAdapter的Update方法将DataSet中的数据更新到数据库中。

csharp

using (SqlConnection conn = new SqlConnection(connectionString))

{

conn.Open();

using (SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM YourTable", conn))

{

SqlCommandBuilder builder = new SqlCommandBuilder(adapter);

DataTable dt = new DataTable();

adapter.Fill(dt);

// 假设DataGridView已经绑定了DataTable

foreach (DataGridViewRow row in dataGridView1.Rows)

{

if (!row.IsNewRow)

{

dt.ImportRow(row.DataBoundItem as DataRow);

}

}

adapter.Update(dt);

}

}

### 方法二:使用Entity Framework

1. **定义实体类**:根据数据库表结构定义实体类。

2. **创建DbContext**:使用Entity Framework的DbContext来操作数据库。

3. **添加数据**:将DataGridView中的数据添加到DbContext的实体集合中。

4. **保存更改**:调用DbContext的SaveChanges方法将更改保存到数据库。

csharp

using (var context = new YourDbContext())

{

foreach (DataGridViewRow row in dataGridView1.Rows)

{

if (!row.IsNewRow)

{

YourEntity entity = new YourEntity();

// 假设DataGridView的每一列对应实体类的一个属性

entity.Property1 = row.Cells["Property1"].Value;

entity.Property2 = row.Cells["Property2"].Value;

// ...

context.YourEntities.Add(entity);

}

}

context.SaveChanges();

}

### 方法三:手动编写SQL语句

1. **构建SQL语句**:根据DataGridView中的数据构建SQL插入、更新或删除语句。

2. **执行SQL语句**:使用SqlCommand执行SQL语句。

csharp

string insertSql = "INSERT INTO YourTable (Column1, Column2) VALUES (@Value1, @Value2)";

string updateSql = "UPDATE YourTable SET Column1 = @Value1 WHERE Column2 = @Value2";

string deleteSql = "DELETE FROM YourTable WHERE Column2 = @Value2";

using (SqlConnection conn = new SqlConnection(connectionString))

{

conn.Open();

using (SqlCommand cmd = new SqlCommand(insertSql, conn))

{

cmd.Parameters.AddWithValue("@Value1", dataGridView1.Rows[0].Cells["Column1"].Value);

cmd.Parameters.AddWithValue("@Value2", dataGridView1.Rows[0].Cells["Column2"].Value);

cmd.ExecuteNonQuery();

}

// ... 重复执行updateSql和deleteSql

}

### 注意事项

- 在执行数据库操作前,确保已经正确配置了数据库连接字符串。

- 根据实际情况选择合适的方法,例如批量操作时使用SqlDataAdapter可能更高效。

- 处理数据库操作时,要注意异常处理,确保程序的健壮性。

- 如果DataGridView中的数据量很大,考虑使用批量操作来提高性能。

通过上述方法,你可以将C# DataGridView中的数据保存到数据库中。在实际开发中,根据具体需求和项目情况选择合适的方法。

更多文章请关注《万象专栏》