从数据库中读取行时发送电子邮件

时间:2016-06-14 16:40:39

标签: c# sql-server

我正在编写一个脚本,它将使用Console.WriteLine输出数据,并为每个“数据集”发送电子邮件。我的问题在于使用:

for (int i = 0; i < reader.FieldCount; i++)
                            {
                                Console.WriteLine(reader.GetValue(i));
                            }

问题:我无法实际保存这些值,因此我也可以在下面的电子邮件脚本中使用它们。

我认为我需要将这些值保存在某种列表中,但我不确定这是否适合采用这种方法。

        try
        {
            cnn.Open();
            //Console.WriteLine("Connection Open!");

            string sql = "SQLQUERY";
            using (var command = new SqlCommand(sql, cnn))
            {
                using (var reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        for (int i = 0; i < reader.FieldCount; i++)
                        {
                            Console.WriteLine(reader.GetValue(i));
                        }

                        SmtpClient client = new SmtpClient();
                        client.Port = 587;
                        client.Host = "HOST";
                        client.EnableSsl = true;
                        client.Timeout = 10000;
                        client.DeliveryMethod = SmtpDeliveryMethod.Network;
                        client.UseDefaultCredentials = false;
                        client.Credentials = new System.Net.NetworkCredential("EMAIL", "PW");

                        MailMessage mm = new MailMessage("donotreply@domain.com", "EMAIL", "TEST", "TEST ");
                        mm.BodyEncoding = UTF8Encoding.UTF8;
                        mm.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;

                        client.Send(mm);

                        Console.WriteLine();
                    }
                }
            }

            Console.WriteLine("A ticket has been generated for the devices listed above.");


            cnn.Close();
        }
        catch (Exception ex)
        {
            Console.WriteLine("Can not open connection!   " + ex);
        }
    }

1 个答案:

答案 0 :(得分:1)

您始终可以使用List<List<object>>并将每一行存储在List<object>个字段中。

// At the top:
List<List<object>> data = new List<List<object>>();

// Lower:
while (reader.Read())
{
    List<object> row = new List<object>();
    for (int i = 0; i < reader.FieldCount; i++)
    {
        object val = reader.GetValue(i);
        Console.WriteLine(val);
        row.Add(val);
    }
    data.Add(row);

    // You can now use the row variable here if you want, or you can
    //    wait until after looping through the reader and send the
    //    emails at the end, using the data variable instead.

    Console.WriteLine();
}