如何将SQL查询的结果存储在变量中?

时间:2015-09-18 20:31:34

标签: c# ado.net

如果您查看下面的代码,您会看到我正在循环查询列表并输出带有结果的查询。

我希望能够将当前输出的内容存储到我可以放在smtp电子邮件正文中的变量或列表中。有没有人有任何想法?

private static void Main()
{
    Console.SetWindowSize(170, 60);

    List<string> queryList = new List<string>(new string[]
    {
        "query 1",
        "query 2",
        "query 3"
    });

    foreach (string query in queryList)
    {
        SqlConnection connection = new SqlConnection("Connection String");

        SqlCommand command = new SqlCommand(query, connection);
        connection.Open();

        SqlDataReader reader = command.ExecuteReader();

        if (reader.HasRows)
        {
            while (reader.Read())
            {
                Console.WriteLine();
                Console.WriteLine(query  + Environment.NewLine + "{0}", reader.GetString(0));
            }
        }
        else
        {
            Console.WriteLine("No rows found.");
        }
        reader.Close();
    }

    Console.WriteLine(Environment.NewLine + "Press any key to exit...");
    Console.ReadKey();
}

1 个答案:

答案 0 :(得分:0)

正如您使用列表来存储要执行的查询一样,您也可以使用列表来存储查询结果

List<string> results = new List<string>();
foreach (string query in queryList)
{
    using(SqlConnection connection = new SqlConnection("Connection String"))
    using(SqlCommand command = new SqlCommand(query, connection))
    {
         connection.Open();
         using(SqlDataReader reader = command.ExecuteReader())
         {
            if (reader.HasRows)
            {
                while (reader.Read())
                {
                    results.Add(query + Environment.NewLine + reader.GetString(0));
                }
            }
            else
            {
                results.Add(query + Environment.NewLine + "No rows found";
            }
        }
    }
}

不要忘记在用于查询数据库的一次性对象周围应用正确的using语句。此外,了解更多有关查询的信息可能会产生更好的方法,创建一批命令以传递到数据库引擎并使用SqlDataReader

NextResult方法检索结果

例如,假设您的查询是这样的:

 SELECT FIELD1 FROM TABLE1
 SELECT FIELD1 FROM TABLE2
 SELECT FIELD1 FROM TABLE3

然后您可以尝试以这种方式将字符串连接在一起(删除foreach循环和多个连接,命令和datareader实例)

 string queries = string.Join(";", queryList.ToArray());
 using(SqlConnection connection = new SqlConnection("Connection String"))
 using(SqlCommand command = new SqlCommand(query, connection))
 {
    connection.Open();
    using(SqlDataReader reader = command.ExecuteReader())
    {
        do
        {
            if (dr.HasRows)
            {
                results.Add(query)
                while (dr.Read())
                {
                    results.Add(Environment.NewLine + reader.GetString(0));
                }
            }
            else
                results.Add(query + Environment.NewLine + "No rows found);
        }
        while (dr.NextResult());
    }
}