避免在C#中嵌套查询

时间:2015-04-14 06:26:56

标签: c# sql loops

目前我正在使用C#代码在gridview中显示基于几个条件的数据。所以,我必须嵌套gridview。我的代码是这样的。

con.ConnectionString = ConfigurationManager.ConnectionStrings["mySQLConnection"].ToString();
con.Open();

            SqlCommand cmd = new SqlCommand("SELECT uname FROM vusers", con);
            var dr = cmd.ExecuteReader();


            if (dr.HasRows)
            {
                while (dr.Read())
                {


        con1.ConnectionString = ConfigurationManager.ConnectionStrings["mySQLConnection"].ToString();
        con1.Open();

                SqlCommand cmd1 = new SqlCommand("SELECT mydata FROM vdata where uname="+dr["uname"].ToString(), con1);
                var dr1 = cmd1.ExecuteReader();


                if (dr1.HasRows)
                {
                        while (dr1.Read())
                        {
                            getmydata = dr1["mydata"].ToString();
                    }
                }

        con2.ConnectionString = ConfigurationManager.ConnectionStrings["mySQLConnection"].ToString();
        con2.Open();

                SqlCommand cmd2 = new SqlCommand("SELECT mynewdata FROM vnewdata where uname="+dr["uname"].ToString(), con2);
                var dr2 = cmd2.ExecuteReader();


                if (dr2.HasRows)
                {
                        while (dr2.Read())
                        {
                            getmynewdata = dr2["mydata"].ToString();
                    }
                }
                }
            }

在上面的代码中,从外部SQL查询中,我得到了uname&在uname的基础上,我从2个内部SQL查询中获取数据。这是2慢和&大数据库的耗时过程。如何防止循环中的2内部查询执行。我怎样才能使它高效率减少时间和资源消耗?

1 个答案:

答案 0 :(得分:0)

您不需要三个连接对象并运行查询三次您可以在单个查询中实现这些值

           SqlConnection con = new SqlConnection();
            con.ConnectionString = ConfigurationManager.ConnectionStrings["mySQLConnection"].ToString();
            con.Open();
            // As per @fubo's comment
            SqlCommand cmd = new SqlCommand("SELECT uname, mydata,mynewdata FROM vusers u JOIN vdata v ON u.uname = v.uname JOIN vnewdata n ON u.uname = n.uname", con);
            using (var dr = cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection))
                if (dr.HasRows)
                {
                    while (dr.Read())
                    {
                        var getmydata = dr["mydata"].ToString();
                        var getmynewdata = dr["mydata"].ToString();
                    }
                }