将结果从 winform DataGridView 写入数据库表的速度非常慢



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

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

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

PS:什么是DGV

最新更新