Hi @Rajkumar Rao ,
Try using SqlTransaction Class to submit all insertion operations at once to reduce database I/O operations and improve performance.
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
using (SqlTransaction transaction = conn.BeginTransaction())
{
try
{
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (row.IsNewRow) continue; // 跳过新行
string column1Value = row.Cells["Column1"].Value.ToString();
string column2Value = row.Cells["Column2"].Value.ToString();
string column3Value = row.Cells["Column3"].Value.ToString();
string column4Value = row.Cells["Column4"].Value.ToString();
string query = "INSERT INTO YourTableName (Column1, Column2, Column3, Column4) VALUES (@Column1, @Column2, @Column3, @Column4)";
using (SqlCommand command = new SqlCommand(query, conn, transaction))
{
command.Parameters.AddWithValue("@Column1", column1Value);
command.Parameters.AddWithValue("@Column2", column2Value);
command.Parameters.AddWithValue("@Column3", column3Value);
command.Parameters.AddWithValue("@Column4", column4Value);
command.ExecuteNonQuery();
}
}
transaction.Commit();
}
catch (Exception ex)
{
transaction.Rollback();
}
}
}
Best Regards.
Jiachen Li
If the answer is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.