0

我有一个未绑定到 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;
        }
    }  
4

1 回答 1

3

打开一次连接,然后执行所有命令,然后关闭数据库连接。这应该可以节省相当多的时间。

此外,您可以尝试创建事务并将所有命令作为事务的一部分运行。根据您使用的数据库引擎,这可能会进一步加快速度。

PS:什么是DGV

于 2012-06-09T22:17:52.527 回答