使用数据读取器中的检查空值更新表

时间:2018-10-28 09:53:08

标签: c# loops while-loop sqldatareader

我的两列电子邮件和tableemail上的状态我曾经使用数据读取器来计算邮件地址并发送邮件:

>  OleDbCommand cmd = null;
>             OleDbCommand cmd2 = null;
>             
>             string queryString = "select email,status from tableemail";
>             using (OleDbConnection connection = new OleDbConnection("Provider = OraOLEDB.Oracle.1; Data Source = xe;
> Password=eppspps;User ID = xpress; unicode=true"))
>             {
>                 OleDbCommand command= new OleDbCommand(queryString, connection);
>                 connection.Open();
>                 cmd = new OleDbCommand(queryString);
>                 cmd.Connection = connection;
>                 OleDbDataReader reader = cmd.ExecuteReader();
>                
>                 while (reader.Read())
>                     
>                 {
>                     MailAddress to = new MailAddress(reader[0].ToString());
>                     message.To.Add(to);     
>                 }

此代码很好用,但是
在数据读取器上检查为空值后,我需要将状态数据更新到表邮件中

> if (!reader.IsDBNull(1))
>                 {
>                     cmd2 = new OleDbCommand(" UPDATE tableemail set status=1 where status is null", connection);
>                     cmd2.ExecuteNonQuery();
>                 }

1 个答案:

答案 0 :(得分:0)

我认为您可以尝试仅使用cmd来执行selectupdate,并删除If(!reader.IsDBNull(1))并将update代码移到外循环。

OleDbCommand cmd = null;

string queryString = "select email,status from tableemail";
using (OleDbConnection connection = new OleDbConnection("Provider = OraOLEDB.Oracle.1; Data Source = xe;
 Password=eppspps;User ID = xpress; unicode=true"))
{
 OleDbCommand command= new OleDbCommand(queryString, connection);
 connection.Open();
 cmd = new OleDbCommand(queryString);
 cmd.Connection = connection;
 OleDbDataReader reader = cmd.ExecuteReader();

 while (reader.Read()) 
 {
     MailAddress to = new MailAddress(reader[0].ToString());
     message.To.Add(to);     
 }
  cmd.CommandText = " UPDATE tableemail set status=1 where status is null";
  cmd.ExecuteNonQuery();
}

编辑

如果您要在while循环中使用update,可以尝试使用另一个OleDbCommand并在if中执行更新

string queryString = "select email,status from tableemail";
string updateString = "UPDATE tableemail set status=1 where email = @email";
using (OleDbConnection connection = new OleDbConnection("Provider = OraOLEDB.Oracle.1; Data Source = xe;
 Password=eppspps;User ID = xpress; unicode=true"))
{
 connection.Open();
 OleDbCommand cmd = new OleDbCommand(queryString,Connection);
 OleDbCommand cmd2 = new OleDbCommand(updateString,Connection);
 OleDbDataReader reader = cmd.ExecuteReader();

 while (reader.Read()) 
 {
     MailAddress to = new MailAddress(reader[0].ToString());
     message.To.Add(to);     
     if(!reader.IsDBNull(1)){
         cmd2.Parameters.Clear();
         cmd2.Parameters.Add(new OleDbParameter("email", reader["email"]));
         cmd2.ExecuteNonQuery();
     }
  }
}