简体   繁体   中英

How do I update rows in my database as I loop through reading them?

I have the following code which loops through a database table and sends emails to the address stored in each row. How can I modify it to update an additional column at the same time as it reads them? I want to update each row with a DateSent value of the current date and time. The table contains five columns - ID, FirstName, LastName, Email, DateSent - and it's the last column I want to update with the date and time the specific email was sent.

I'm still new to this so apologies if this is basic beginners stuff.

Thanks.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Net.Mail;

public partial class displayRecords : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
      string strConn = "my connection string;";
      string strSQL = "select * from EmailTable";
      SqlConnection objConnection = new SqlConnection(strConn);
      SqlCommand objCommand = new SqlCommand(strSQL, objConnection);
      objConnection.Open();
      SqlDataReader objReader = objCommand.ExecuteReader();
      while (objReader.Read())
      {

        MailMessage myMessage = new MailMessage();
        myMessage.Subject = "Test Message for " + (objReader.GetValue(1)) + " " + (objReader.GetValue(2));
        myMessage.Body = "This email would be sent to: " + (objReader.GetValue(3));
        myMessage.From = new MailAddress("senderaddress@mydomain.com", "Sender Name");
        myMessage.To.Add(new MailAddress((objReader.GetString(3)), (objReader.GetString(2))));

        SmtpClient mySmtpClient = new SmtpClient();
        mySmtpClient.Send(myMessage);

        Response.Write("Email sent to: " + (objReader.GetValue(3)) + "<br>");
      }
      objReader.Close();
      objConnection.Close();
    }

}

You can use an UPDATE statement to update the row based on the id.

  while (objReader.Read())
  {

    MailMessage myMessage = new MailMessage();
    myMessage.Subject = "Test Message for " + (objReader.GetValue(1)) + " " + (objReader.GetValue(2));
    myMessage.Body = "This email would be sent to: " + (objReader.GetValue(3));
    myMessage.From = new MailAddress("senderaddress@mydomain.com", "Sender Name");
    myMessage.To.Add(new MailAddress((objReader.GetString(3)), (objReader.GetString(2))));

    SmtpClient mySmtpClient = new SmtpClient();
    mySmtpClient.Send(myMessage);

    Response.Write("Email sent to: " + (objReader.GetValue(3)) + "<br>");

    // Update the table, assuming ID is the first column in the table.
    // This is for demonstration only and it is not the most efficient way
    // of doing this because a new command is created each time. 
    // The correct way would be to move the command and parameters creation
    // outside the loop and just update the parameter values inside the loop.
    SqlCommand UpdateCommand = new SqlCommand("UPDATE EmailTable SET DateSent = @dtSent WHERE id = @thisId", objConnection);
    updateCommand.Parameters.AddWithValue( "@dtSent", DateTime.Now);
    updateCommand.Parameters.AddWithValue( "@thisId", objReader.GetValue(0));
    updateCommand.executeNonQuery();
  }

I've managed to get it working now using the code below which opens a second connection within the first. This is probably a terribly inefficient way of doing things, so I'll look into DataAdapters and DataSets, but at least it works for now.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Net.Mail;

public partial class displayRecords : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
      string strConn = "my connection string";
      string strSQL = "select * from EmailTable where Sent = 0";
      SqlConnection objConnection = new SqlConnection(strConn);
      SqlCommand objCommand = new SqlCommand(strSQL, objConnection);
      objConnection.Open();
      SqlDataReader objReader = objCommand.ExecuteReader();
      while (objReader.Read())
      {

        MailMessage myMessage = new MailMessage();
        myMessage.IsBodyHtml = true;
        myMessage.Subject = "Test Message for " + (objReader.GetValue(1)) + " " + (objReader.GetValue(2));
        myMessage.Body = "<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'> <html xmlns='http://www.w3.org/1999/xhtml'> <head> <meta http-equiv='Content-Type' content='text/html; charset=utf-8' /> <title>Untitled Document</title> <style type='text/css'> body p {  font-family: Verdana, Geneva, sans-serif; } body p {    font-size: small; } </style> </head>  <body> <p>Hello " + (objReader.GetValue(1)) + "</p> <p>This is a test email which will be sent to your email address: " + (objReader.GetValue(3)) + " when the system is live.</p> <p>Thanks.</p> </body> </html>";
        myMessage.From = new MailAddress("senderaddress@mydomain.com", "Sender Name");
        myMessage.To.Add(new MailAddress((objReader.GetString(3)), (objReader.GetString(2))));

        SmtpClient mySmtpClient = new SmtpClient();
        mySmtpClient.Send(myMessage);

        Response.Write("Email sent to: " + (objReader.GetValue(3)) + "<br>");

        // Update the table, assuming ID is the first column in the table.
        // This is for demonstration only and it is not the most efficient way
        // of doing this because a new command is created each time. 
        // The correct way would be to move the command and parameters creation
        // outside the loop and just update the parameter values inside the loop.
        string strConn2 = "my connection string";
        SqlConnection objConnection2 = new SqlConnection(strConn2);
        SqlCommand UpdateCommand = new SqlCommand("UPDATE EmailTable SET Sent = 1, DateSent = @dtSent WHERE id = @thisId", objConnection2);
        objConnection2.Open();
        UpdateCommand.Parameters.AddWithValue("@dtSent", DateTime.Now);
        UpdateCommand.Parameters.AddWithValue("@thisId", objReader.GetValue(0));
        UpdateCommand.ExecuteNonQuery();
        objConnection2.Close();
      }
      objReader.Close();
      objConnection.Close();
    }

}

Don't use a DataReader. Use DataAdapter to fill up a DataSet, then loop through that and update the DateSent column. After loop, update the DataSet.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM