I’ve got a DataGridView (DGV) that is not bound to a table in SQL Server CE.
An ‘Update DB’ button on the WinForm then calls the following method PushFromDGV. This then clears the table HelloWorld and then runs through the items in the DGV inserting them into HelloWorld
There are approx 1000 rows in the DGV and it takes a couple of minutes to run.
Do I really have to do 1000 round trips to write the data to the db table or is there a way I can do it in one trip?
private void PushFromDGV()
{
ExecCommand(@"DELETE FROM HELLOWORLD");
for (int i = 0; i < uxExperimentDGV.RowCount-1; ++i)
{ //iterate for every row in the DGV
ExecCommand(@"INSERT INTO HELLOWORLD SELECT '" + (string)uxExperimentDGV[0, i].Value + "'");
}
}
public void ExecCommand(string myCommand)
{
// Open the connection
try
{
using (SqlCeConnection conn = new SqlCeConnection(ConfigurationManager.ConnectionStrings["DatabaseDGVexperiments.Properties.Settings.DatabaseDGVexperimentsConnStg"].ConnectionString)) // conn.Open();
{// 1. Instantiate a new command with a query and connection
conn.Open();
SqlCeCommand cmd = new SqlCeCommand(myCommand, conn);
cmd.CommandText = myCommand; // 2. Set the CommandText property
cmd.Connection = conn; // 3. Set the Connection property
cmd.ExecuteNonQuery(); // 4. Call ExecuteNonQuery to send command
}
}
catch (Exception ex)
{
MessageBox.Show((string)ex.Message);
return;
}
}
It has been suggested to just make the open connection once before the loop and then close it after the loop. I now have the following.
Is this an accurate interpretation
?
public SqlCeConnection conn = new SqlCeConnection(ConfigurationManager.ConnectionStrings["DatabaseDGVexperiments.Properties.Settings.DatabaseDGVexperimentsConnStg"].ConnectionString);
private void PushFromDGV()
{
conn.Open();
ExecCommand(@"DELETE FROM HELLOWORLD");
for (int i = 0; i < uxExperimentDGV.RowCount - 1; ++i)
{ //iterate for every row in the DGV
ExecCommand(@"INSERT INTO HELLOWORLD SELECT '" + (string)uxExperimentDGV[0, i].Value + "'");
}
conn.Close();
}
public void ExecCommand(string myCommand)
{
try
{
SqlCeCommand cmd = new SqlCeCommand(myCommand, conn);
cmd.CommandText = myCommand;
cmd.Connection = conn;
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show((string)ex.Message);
return;
}
}
Open your connection once, then execute all of your commands, and then close your database connection. This should save quite some time.
Moreover, you can try creating a transaction and running all commands as a part of the transaction. Depending on the database engine you’re using, this may speed things further up.
P.S.: What is a DGV?