c# - 更新记录时性能非常慢

标签 c# performance postgresql

我正在编写连接到数据库的 C# 应用程序,进行配对选择,然后将记录插入回网络中的服务器。

但是我有大约 40k 条记录,我的程序处理一条记录大约需要 1 秒。

我不知道如何提高性能。这是我的 sql getter 和 inserter。有什么建议吗?

    public bool insert_and_ConfirmSQL(String Query, String comments)
    {
        bool success = false;
        NpgsqlCommand cmd = new NpgsqlCommand();
        NpgsqlConnection mycon = new NpgsqlConnection();
        string connstring = String.Format("Server={0};Port={1}; User Id={2};Password={3};Database={4};", tbHost, tbPort, tbUser, tbPass, tbDataBaseName);
        mycon.ConnectionString = connstring;
        cmd = mycon.CreateCommand();
        cmd.CommandText = Query;
        mycon.Open();

        int temp = 0;
        try
        {
            temp = cmd.ExecuteNonQuery();
            success = true;
        }
        catch
        {
            success = false;
        }
        finally
        {
            if (mycon.State.ToString() == "Open")
            {
                mycon.Close();
            }
        }
        return success;
    }


    public String getString(String sql, NpgsqlConnection conn)
    {
        using (DataSet ds = new DataSet())
        {
            using (NpgsqlDataAdapter da = new NpgsqlDataAdapter(sql, conn))
            {
                da.Fill(ds);
                if (ds.Tables.Count > 0)
                {
                    DataTable dt = ds.Tables[0];
                    //  check count of Rows 
                    if (dt.Rows.Count > 0)
                    {
                        object o = dt.Rows[0][0];
                        if (o != DBNull.Value && o != null)
                        {
                            return o.ToString();
                        }
                    }
                }
            }
        }
        // Return default value 
        return "";
    }

最佳答案

没有机会帮助您处理 sql 语句,因为我们不知道它们。

唯一(猜测)可见的问题是您试图每次都使用新连接循环获取 40K 记录(您知道如何)。作为您的代码提供的两个例程正是这样做的。那么,您是否需要 40K 次调用 insert_and_ConfirmSQL 和/或另外 40K 次调用 getString 例程?

如果你真的循环,那么更新你的代码以只使用一个连接而不关闭它;数据集也可以这样做(使用前必须清除它:ds.Clear())。

不用说,如果您的查询很大(就数据而言),和/或索引没有覆盖查询,那么延迟是意料之中的。

尝试使用这种方法并告诉我们。

关于c# - 更新记录时性能非常慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11160187/

相关文章:

c# - 空传播运算符和扩展方法

c# - 将文件夹移动到 UWP 中另一个位置的最快方法

postgresql - 如何将集合返回函数的输出插入到表中

sql - 如何根据 ActiveRecord 中的条件在每第 n 个项目中插入?

c# - 如何使用 .NET 以编程方式将信息发送到 C# 中的 Web 服务?

C#如何Regex.Replace "\r\n"(实际字符,不是换行符)

c++ - 在 C++ 中存储、加载和使用倒排索引的最佳方式 (~500 Mo)

Javascript:多次调用对象属性

Django bulk_create 忽略导致 IntegrityError 的行?

c# - jQuery 运行时错误 : Function Expected