我正在尝试从数据库中选择一个用户列表,并根据条件向每个用户发送电子邮件 isSent == false。向他们发送电子邮件后,此 false 的值应更新为 true。下面的代码是我从数据库中检索用户列表并调用方法 sendEmail() 到他们每个人的方式。
myConnection.Open();
//*******
try
{
SqlDataReader myReader = null;
string sql = "SELECT * FROM testTable where isSent = false";
SqlCommand myCommand = new SqlCommand(sql, myConnection);
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
sendEmail(myReader["emailAdd"].ToString(),
myReader["UserID"].ToString());
}
第二部分:
public static void sendEmail(string emailAdd,string userID){
.
.
.
try
{
smtpClient.Send(mail);
try
{
string sql = "UPDATE testTable SET isSent = 1 WHERE UserID = " + userID;
SqlCommand myCommand = new SqlCommand(sql, myConnection);
int rows = myCommand.ExecuteNonQuery();
.
.
.
}
}
}
我面临的问题是,由于从主方法中我已经按住 SqlDataReader 进行读取,因此我现在无法更新。有什么解决方法吗?我收到的错误消息如下:
There is already an open DataReader associated with this Command which must be closed first.
我面临的问题是,由于从主方法中我已经按住 SqlDataReader 进行读取,因此我现在无法更新。有什么解决方法吗?
这只是一个问题,因为您正在共享连接(myConnection
)。别这样。每次要执行数据库操作时,创建一个新SqlConnection
,并让连接池基础结构进行处理以使其高效。此外,对数据库相关资源使用 using
语句:
using (var connection = new SqlConnection(...))
{
using (var command = new SqlCommand(...))
{
using (var reader = command.ExecuteReader(...))
{
...
}
}
}
作为另一种选择。可以将其添加到数据库的连接字符串中。
MultipleActiveResultSets=True
性能略有下降。而且它在较旧的SQL Server中不受支持。我认为在2005年之前
试试这段代码。`
public static void sendEmail(string emailAdd,string userID){
try
{
SqlConnection con = new SqlConnection(@"");
con.Open();
MailMessage mail = new MailMessage("example@gmail.com", emailAdd);
SmtpClient smtpClient = new SmtpClient();
NetworkCredential nc = new NetworkCredential("example@gmail.com", "test");
smtpClient.Port = 587;
smtpClient.Host = "smtp.gmail.com";
smtpClient.EnableSsl = true;
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.UseDefaultCredentials = false;
// smtpClient.Host = "smtp.google.com";
mail.Subject = "this is a test email.";
mail.Body = "this is my test email body";
smtpClient.Credentials = nc;
smtpClient.Send(mail);
using (SqlCommand cmd = con.CreateCommand())
{
string sql = "UPDATE TestTable SET IsSent = 'true' WHERE UserID = " + userID;
SqlCommand myCommand = new SqlCommand(sql, con);
int rows = myCommand.ExecuteNonQuery();
}
}
catch(Exception e)
{
string message = e.Message;
}`
}