【问题标题】:Querying data from two databases in C#在 C# 中从两个数据库中查询数据
【发布时间】:2017-09-13 11:11:20
【问题描述】:

我目前有一个查询,我从 2 个不同的数据库中获取数据,这些数据被附加到一个名为“accountbuys”的列表中。

  1. 我的第一个表有三个数据条目(3个想买股票的账户

  2. 下一张表有 17 个数据点(17 只股票要买)

我正在合并这些表并获得输出

但是,我想要的输出应该有 17 个数据点,每次重复 3 个不同的帐户,以便最终用户可以向下钻取并购买他想要的任何股票

PS:如果我想问的不是很清楚,请礼貌地告诉我。请尽量不要粗鲁,我还在学习 StackExchange 的新手!

这是我的代码:`

public List<BuySellModel> GetBuyDataWthAccount()
{
    List<BuySellModel> accountbuys = new List<BuySellModel>();

    using (SqlConnection connectionreit = new SqlConnection(HubConnection))
    using (SqlConnection connection = new SqlConnection(PMConnection))

    {

        connectionhub.Open();
        connection.Open();

        SqlCommand command3 = new SqlCommand(@"SELECT distinct(table1.name) as 'Symbol' ,table2.Segment as 'Segment',table2.AllocationAmount as 'AllocationAmount',table2.PX_LAST as 'Price', 
                                                    table1.CUR_MKT_CAP as 'CMC',table1.FCFY_WITH_CUR_MKT_CAP as 'FCMC',table1.ROIC as 'ROIC', table1.ROICDELTA as 'ROICD' FROM View_REIT_Model_And_Holdings as table1
                                                    INNER JOIN [MostRecentlyInModelSelected] as table2
                                                        ON table1.name = table2.Ticker
                                                        WHERE table1.AllocationAmount != -1 AND
                                                        NOT EXISTS (SELECT NULL FROM [ViewPCData] as table3 WHERE table1.name = table3.Symbol AND table2.Segment = table3.SubsectorDescription AND table3.Objective = 'REITS' AND table3.SectorDescription != 'NULL' AND table3.SubsectorDescription != 'NULL')",
                                                    connectionreit);
        command3.CommandType = CommandType.Text;

        SqlCommand command4 = new SqlCommand("SELECT PortfolioAccountNumber, PortfolioDescription, SUM(TotalValue) as 'TotalValue' FROM [ViewPCData] WHERE Objective = 'REITS' GROUP BY PortfolioAccountNumber,PortfolioDescription", connection);
        command4.CommandType = CommandType.Text;

        var reader = command3.ExecuteReader();
        var reader1 = command4.ExecuteReader();

        if (reader1.HasRows)
        {
            while (reader1.Read())
            {
                BuySellModel accountb = new BuySellModel();
                accountb.PortfolioAccount = reader1.GetString(reader1.GetOrdinal("PortfolioAccountNumber"));
                accountb.PortfolioDescription = reader1.GetString(reader1.GetOrdinal("PortfolioDescription"));
                accountb.AccountAmount = reader1.GetDecimal(reader1.GetOrdinal("TotalValue"));
                accountbuys.Add(accountb);

                if (reader.HasRows)
                {
                    //foreach(var account in accountbuys)
                    //{


                    while (reader.Read())
                    {
                        BuySellModel buy = new BuySellModel();
                        buy.Symbol = reader.GetString(reader.GetOrdinal("Symbol"));
                        buy.Segment = reader.GetString(reader.GetOrdinal("Segment"));
                        //if (accountNumber == "soand os")
                        //{
                        //    1/3 of totalaccountvalue
                        buy.AllocationAmount = (reader.GetDouble(reader.GetOrdinal("AllocationAmount")));
                        //}
                        buy.Price = reader.GetDouble(reader.GetOrdinal("Price"));
                        buy.MarketValue = reader.GetDouble(reader.GetOrdinal("CMC"));
                        buy.FCFY = reader.GetDouble(reader.GetOrdinal("FCMC"));
                        buy.ROIC = reader.GetDouble(reader.GetOrdinal("ROIC"));
                        buy.ROICdelta = reader.GetDouble(reader.GetOrdinal("ROICD"));
                        buy.Buy = true;
                        //account1 = account.accountnumber;                   
                        accountbuys.Add(buy);

                    }
                    //} //for loop


                }


            } // accounts
        } //reader1.hasrows

        connectionhub.Close();
        connection.Close();
    }

    return accountbuys;
}

编辑:

将表拆分为两个不同的列表,然后将它们合并。这现在运作良好。似乎也适合缩放。

public List<BuySellModel> GetBuyDataWthAccount()
    {
        List<BuySellModel> accountbuys = new List<BuySellModel>();

        List<Account> accounts = new List<Account>();


        using (SqlConnection connection = new SqlConnection(PMConnection))

        {

            connection.Open();

            SqlCommand command3 = new SqlCommand(@"SELECT distinct(table1.name) as 'Symbol' ,table2.Segment as 'Segment',table2.AllocationAmount as 'AllocationAmount',table2.PX_LAST as 'Price', 
                                                table1.CUR_MKT_CAP as 'CMC',table1.FCFY_WITH_CUR_MKT_CAP as 'FCMC',table1.ROIC as 'ROIC', table1.ROICDELTA as 'ROICD' FROM View_Model_And_Holdings as table1
                                                INNER JOIN [MostRecentlyInModelSelected] as table2
                                                    ON table1.name = table2.Ticker
                                                    WHERE table1.AllocationAmount != -1 AND
                                                    NOT EXISTS (SELECT NULL FROM [ViewPCData] as table3 WHERE table1.name = table3.Symbol AND table2.Segment = table3.SubsectorDescription AND table3.Objective = 'STOCKS' AND table3.SectorDescription != 'NULL' AND table3.SubsectorDescription != 'NULL')",
                                                connectionreit);
          command3.CommandType = CommandType.Text;

          SqlCommand command4 = new SqlCommand("SELECT PortfolioDetail , SUM(TotalValue) as 'TotalValue' FROM [ViewPCData] WHERE Objective = 'STOCKS' GROUP BY PortfolioAccountNumber,PortfolioDescription", connection);
          command4.CommandType = CommandType.Text;

            var reader = command3.ExecuteReader();
            var reader1 = command4.ExecuteReader();
            if (reader1.HasRows)
            {
                while (reader1.Read())
                {
                    Account accountb = new Account();
                    accountb.PortfolioDetail = reader1.GetString(reader1.GetOrdinal("PortfolioDetail"));
                   // accountb.PortfolioDescription = reader1.GetString(reader1.GetOrdinal("PortfolioDescription"));
                    accountb.AccountAmount = reader1.GetDecimal(reader1.GetOrdinal("TotalValue"));

                    accounts.Add(accountb);
                }
            }
            //List<BuyReits> buys = new List<BuyReits>();
            if (reader.HasRows && accounts.Count > 0)
            {
                while (reader.Read())
                {
                    foreach (var acc in accounts)
                    {
                        BuySellModel buy = new BuySellModel();
                        buy.Symbol = reader.GetString(reader.GetOrdinal("Symbol"));
                        buy.Segment = reader.GetString(reader.GetOrdinal("Segment"));
                        buy.AllocationAmount = (reader.GetDouble(reader.GetOrdinal("AllocationAmount")));
                        buy.Price = reader.GetDouble(reader.GetOrdinal("Price"));
                        //buy.Quantity = reader.GetInt32((reader.GetOrdinal("AllocationAmount"))/(reader.GetOrdinal("Price")));
                        buy.MarketValue = reader.GetDouble(reader.GetOrdinal("CMC"));
                        buy.FCFY = reader.GetDouble(reader.GetOrdinal("FCMC"));
                        buy.ROIC = reader.GetDouble(reader.GetOrdinal("ROIC"));
                        buy.ROICdelta = reader.GetDouble(reader.GetOrdinal("ROICD"));
                        buy.Buy = true;
                        buy.PortfolioAccount = acc.PortfolioDetail;
                        buy.AccountAmount = acc.AccountAmount;

                        accountbuys.Add(buy);

                    }

                }
            }

            connection.Close();


        }

        return accountbuys;

    }

【问题讨论】:

  • 你用的是mysql还是sql server?它们不是同一件事。此外,如果您发布有关您的表格的一些详细信息,这将非常有帮助。 spaghettidba.com/2015/04/24/…
  • 通常会要求您准确说明当前代码中的哪些问题。你也有 mysql 和 sql-server 的标签,通常要求你选择一个。
  • 不是很清楚什么不起作用。有什么问题?
  • @SeanLange 谢谢你的链接!这很有帮助。
  • SmithaShivakumar - 您使用的是哪个版本的 .Net?您可以访问 LINQ 库吗?

标签: c# sql asp.net sql-server asp.net-mvc


【解决方案1】:

以下提供了 C# 层中的交叉连接(并不是说它是最好的解决方案,但它让您更接近准备就绪):

using (SqlConnection connectionhub = new SqlConnection(HubConnection))
using (SqlConnection connection = new SqlConnection(PMConnection))

{

    connectionhub.Open();
    connection.Open();

    SqlCommand command3 = new SqlCommand(@"
        SELECT distinct(table1.name) as 'Symbol',
               table2.Segment as 'Segment',
               table2.AllocationAmount as 'AllocationAmount',
               table2.PX_LAST as 'Price', 
               table1.CUR_MKT_CAP as 'CMC',
               table1.FCFY_WITH_CUR_MKT_CAP as 'FCMC',
               table1.ROIC as 'ROIC', 
               table1.ROICDELTA as 'ROICD' 
          FROM View_REIT_Model_And_Holdings as table1
                INNER JOIN [MostRecentlyInModelSelected] as table2
                    ON table1.name = table2.Ticker
         WHERE table1.AllocationAmount != -1 
           AND NOT EXISTS (SELECT NULL 
                             FROM [ViewPCData] as table3 
                            WHERE table1.name = table3.Symbol 
                              AND table2.Segment = table3.SubsectorDescription 
                              AND table3.Objective = 'REITS' 
                              AND table3.SectorDescription != 'NULL' 
                              AND table3.SubsectorDescription != 'NULL')",
                                                connectionreit);
    command3.CommandType = CommandType.Text;

    SqlCommand command4 = new SqlCommand(@"
        SELECT PortfolioAccountNumber, 
               PortfolioDescription, 
               SUM(TotalValue) as 'TotalValue' 
          FROM [ViewPCData] 
         WHERE Objective = 'REITS' 
         GROUP BY PortfolioAccountNumber, PortfolioDescription", connection);
    command4.CommandType = CommandType.Text;

    var stocksDS = new DataSet();
    var stocksDA = new System.Data.SqlClient.SqlDataAdapter();
    stocksDA.SelectCommand = command3
    stocksDA.Fill(stocksDS, "stocks");

    var acctsDS = new DataSet();
    var acctsDA = new System.Data.SqlClient.SqlDataAdapter();
    acctsDA.SelectCommand = command4
    acctsDA.Fill(acctsDS, "accts");

    var stocks = stocksDS.Tables["stocks"].AsEnumerable();
    var accts = acctsDS.Tables["accts"].AsEnumerable();

    var results = (from stocksDR in stocks
                   from acctsDR in accts
                   select new BuySellModel {
                        PortfolioAccount = acctsDR["PortfolioAccountNumber"],
                        PortfolioDescription = acctsDR["PortfolioAccountDescription"],
                        AccountAmount = acctsDR["TotalValue"],
                        Symbol = stocksDR["Symbol"],
                        Segment = stocksDR["Segment"],
                        AllocationAmount = stocksDR["AllocationAmount"],
                        Price = stocksDR["Price"],
                        MarketValue = stocksDR["CMC"],
                        FCFY = stocksDR["FCMC"],
                        ROIC = stocksDR["ROIC"],
                        ROICdelta = stocksDR["ROICD"],
                        Buy = true
                    });

    foreach (BySellModel buy in results) {
        accountBuys.Add(buy);
    }

    connectionhub.Close();
    connection.Close();
}

编辑:删除有问题的括号。

【讨论】:

  • 谢谢你!我收到“System.Data.dll 中发生'System.ArgumentException' 类型的异常,但未在用户代码中处理”的错误,我错过了什么吗?我确实有“ConfigurationManager.ConnectionStrings”设置..
  • 它在哪一行报告错误?另外,您是否在文件顶部添加了using System.Data.DataSetExtensions;?您可能还需要在项目中添加对 DLL 的引用。
  • 它在 var 结果结束时给了我整个“select new BuySellModel()”块的错误。它还给出了这一点 - “附加信息:列 'PortfolioAccountDescription' 不属于表帐户。”
  • 我的代码不接受“使用 System.Data.DataSetExtensions”,它说 System.Data 中不存在 DataExtensions
  • 要使 DataSetExtensions 可用,您需要在项目中找到并添加对 System.Data.DataSetExtensions.dll 的引用。至于select new BuySellModel() 的错误,我可能过于急切,您无法从 linq 查询中选择静态类型 - 在 BuySellModel 之后不带 () 尝试。
【解决方案2】:

在不更改任何 C# 代码的情况下,可以通过将 SQL 查询从 INNER JOIN 查询更改为 CROSS JOIN 查询来获得所需的内容。

关于这种方法的一些注意事项:

  1. 如果包含 WHERE 子句,查询将充当 INNER JOIN。

  2. 交叉连接可能会显着变慢,因为查询正在寻找所有可能的组合。只有 51 (3 * 17) 种组合可用,这不是一个大问题,但如果您希望将其扩展到更多客户和股票,那么性能会变得越来越差

【讨论】:

  • 是的,我希望扩大规模,因为我可能拥有更多客户。
猜你喜欢
  • 1970-01-01
  • 2012-01-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多