SQL Server CEのテーブルにバインドされていないDataGridView(DGV)があります。次に、WinFormの[DBの更新]ボタンは、次のメソッドを呼び出しますPushFromDGV
。次に、これによりテーブルがクリアHelloWorld
され、DGV内のアイテムが実行されてそれらが挿入されます。HelloWorld
DGVには約1000行あり、実行には数分かかります。
データをdbテーブルに書き込むために本当に1000回のラウンドトリップを実行する必要がありますか、それとも1回のトリップでそれを実行できる方法はありますか?
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;
}
}
ループの前に一度だけ接続を開いてから、ループの後で接続を閉じることをお勧めします。私は今、次のものを持っています。
これは正確な解釈ですか
?
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;
}
}