在ASP.NET MailMessage类中发送SQL Select作为MailMessage正文的结果的想法

时间:2018-09-28 18:47:52

标签: c# sql asp.net

因此,假设我具有以下选择:SELECT TITLES FROM DOCUMENTS WHERE AC_DATE = GETDATE()

在我的.cs代码中,就像这样

con.Open();
string query = "SELECT TITLES FROM DOCUMENTS WHERE AC_DATE = GETDATE()"
SqlCommand cmd = new SqlCommand(query, con);
SqlDataReader sdr = cmd.ExecuteReader();

它将从我的表中返回一些标题。我需要在mailMessage.Body = "";上插入来自我的选择的所有这些记录,才能通过电子邮件发送给某些人,但是我该怎么做?

1 个答案:

答案 0 :(得分:2)

您可以在SqlDataReader中循环结果并将标题添加到字符串中。

//create a stringbuilder
StringBuilder sb = new StringBuilder();

//create a connection to the database 
using (SqlConnection connection = new SqlConnection(Common.connectionString))
using (SqlCommand command = new SqlCommand("SELECT TITLES FROM DOCUMENTS WHERE AC_DATE = GETDATE()", connection))
{
    //open the connection
    connection.Open();

    //create a reader
    SqlDataReader reader = command.ExecuteReader();

    //loop all the rows in the database
    while (reader.Read())
    {
        //add the title to the stringbuilder
        sb.AppendLine(reader["TITLES"].ToString());
    }
}

//create the mail message with the titles
mailMessage.Body = sb.ToString();