当我循环读取它们时,如何更新数据库中的行?

时间:2022-12-17 07:24:35

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.

我有以下代码循环数据库表并将电子邮件发送到存储在每行中的地址。如何修改它以在读取它们的同时更新其他列?我想用当前日期和时间的DateSent值更新每一行。该表包含五列--ID,FirstName,LastName,Email,DateSent - 这是我想要更新的最后一列,其中包含特定电子邮件的发送日期和时间。

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();
    }

}

3 个解决方案

#1


1  

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

您可以使用UPDATE语句根据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();
  }

#2


0  

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.

不要使用DataReader。使用DataAdapter填充DataSet,然后遍历它并更新DateSent列。循环后,更新DataSet。

#3


0  

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.

我已经设法使用下面的代码使其工作,在第一个中打开第二个连接。这可能是一种非常低效的处理方式,因此我将研究DataAdapters和DataSet,但至少它现在可以工作。

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();
    }

}

#1


1  

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

您可以使用UPDATE语句根据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();
  }

#2


0  

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.

不要使用DataReader。使用DataAdapter填充DataSet,然后遍历它并更新DateSent列。循环后,更新DataSet。

#3


0  

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.

我已经设法使用下面的代码使其工作,在第一个中打开第二个连接。这可能是一种非常低效的处理方式,因此我将研究DataAdapters和DataSet,但至少它现在可以工作。

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();
    }

}