使用太多连接优化SQL语句

时间:2016-09-04 21:46:24

标签: c# mysql sql

我编写了下面的代码,但由于content.mDName.Count超过30k,所以它太网络消耗了。任何人都可以帮我找到如何优化它以减少迭代次数的替代方案吗?

    public List<int> GetMDIB([FromBody] MD content)
    {

        var values = new List<int>();

        for (int i = 0; i < content.mDName.Count; i++)
        {
            using (var conn = new MySqlConnection(BasicAuthHttpModule.connectionString))
            using (var cmdgetall = conn.CreateCommand())
            {
                conn.Open();

                cmdgetall.CommandText = "SELECT tbmd.mdID FROM tbmd WHERE tbmd.mdDFID = " + content.dFID[i] + " AND tbmd.mdName = '" + content.mDN[i] + "';";
                using (var reader = cmdgetall.ExecuteReader())
                {
                    if (reader.Read())
                        values.Add(reader.GetInt32(reader.GetOrdinal("mdID")));
                    else
                        values.Add(-1);
                }
                conn.Close();
            }
        }
        return values;
    }

试用1(不工作):

        using (var conn = new MySqlConnection(BasicAuthHttpModule.connectionString))
        using (var cmdgetall = conn.CreateCommand())
        {
            conn.Open();

            whr = "SELECT IFNULL(tbmd.mdID,-1) FROM tbmd WHERE ";


            for (int i = 0; i < content.mDN.Count; i++)
            {

                whr = whr + "(tbmd.mdDFID = " + content.dFID[i] + " AND tbmd.mdName = '" + content.mDN[i] + "') ";

                if (i < content.mDName.Count - 1)
                    whr = whr + "OR ";
                else
                    whr = whr + ";";
            }

            cmdgetall.CommandText = whr;


            using (var reader = cmdgetall.ExecuteReader())
            {
                if (reader.Read())
                {
                    values.Add(reader.GetInt32(reader.GetOrdinal("mdID")));
                }
                else
                    values.Add(-1);
            }
            conn.Close();
        }

0 个答案:

没有答案