我有一个未绑定到 SQL Server CE 中的表的 DataGridView (DGV)。WinForm 上的“更新数据库”按钮然后调用以下方法PushFromDGV
。然后这会清除表HelloWorld
,然后遍历 DGV 中的项目,将它们插入HelloWorld
DGV 中大约有 1000 行,运行需要几分钟。
我真的必须做 1000 次往返才能将数据写入 db 表,还是有一种方法可以一次完成?
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;
}
}