使用循环c#

时间:2019-03-06 08:25:17

标签: c#

我有一个Windows窗体程序,用于管理业务。我将所有客户详细信息保留在链接的数据库中。电子邮件地址。我有一个按钮,可让我向邮件列表中的所有人发送电子邮件(以下代码)。但是在发送了一些带有未指定错误的电子邮件后,它崩溃了。我不知道为什么?我需要它立即从CustomerID40-CustomerID1425向所有客户发送相同的电子邮件,我们将不胜感激。对不起,如果代码混乱。谢谢。 错误:

  

System.Data.OleDb.OleDbException

     

HResult = 0x80004005

     

Message =未指定错误

     

Source = System.Data

     

StackTrace:

     在

  System.Data.OleDb.OleDbConnectionInternal..ctor(OleDbConnectionString   constr,OleDbConnection连接)

     在

  System.Data.OleDb.OleDbConnectionFactory.CreateConnection(DbConnectionOptions   选项,DbConnectionPoolKey poolKey,对象poolGroupProviderInfo,   DbConnectionPool池,DbConnection owneringObject)

     在

  System.Data.ProviderBase.DbConnectionFactory.CreateConnection(DbConnectionOptions   选项,DbConnectionPoolKey poolKey,对象poolGroupProviderInfo,   DbConnectionPool池,DbConnection owningConnection,   DbConnectionOptions userOptions)

     在

  System.Data.ProviderBase.DbConnectionFactory.CreateNonPooledConnection(DbConnection   owningConnection,DbConnectionPoolGroup,poolGroup,DbConnectionOptions   userOptions)

     在

  System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection   owningConnection,TaskCompletionSource`1重试,DbConnectionOptions   userOptions,DbConnectionInternal oldConnection,DbConnectionInternal&   连接)

     在

  System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection   externalConnection,DbConnectionFactory connectionFactory,   TaskCompletionSource`1重试,DbConnectionOptions userOptions)

     在

  System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection   externalConnection,DbConnectionFactory connectionFactory,   TaskCompletionSource`1重试,DbConnectionOptions userOptions)

     在

  System.Data.ProviderBase.DbConnectionInternal.OpenConnection(DbConnection   externalConnection,DbConnectionFactory connectionFactory)

     

在System.Data.OleDb.OleDbConnection.Open()

     

位于CourseworkDatabase.clsDBConnector.Connect()中   C:\ Users \ rep \ OneDrive \ Desktop \ Repairs \ Repairs_Database \ CourseworkDatabase \ CourseworkDatabase \ clsDBConnector.cs:第18行

代码:

private void button6_Click_1(object sender, EventArgs e)
{
    DialogResult dialogResult = MessageBox.Show("Are you sure to send email to all customers?(check code)", "Warning", MessageBoxButtons.YesNo);​
    if (dialogResult == DialogResult.Yes)​
    {
        DoButtonTask();​
    }​
}​​
private void DoButtonTask()
{
    for (int i = 40; i < 1425; i++)​ //40-1425 is customerID's
    {
        clsDBConnector dbConnector1 = new clsDBConnector();​
        OleDbDataReader dr1;​
        string sqlStr1;​
        dbConnector1.Connect();​
        sqlStr1 = " SELECT CustomerID, DateAdded, FullName, PhoneNumber, EmailAddress, SendOffersByEmail"​ +
            " FROM Customer" + ​
            " WHERE (CustomerID = " + i + ")";​
        dr1 = dbConnector1.DoSQL(sqlStr1);​
        string name = "";​
        string CustomerID = "";​
        string email = "";​
        string SendOffersBy_Email = "";​
        DateTime date = DateTime.Now;​
        while (dr1.Read())
        {    ​
            CustomerID = CustomerID + Convert.ToString(dr1[0]);​
            name = name + dr1[2];​
            email = email + Convert.ToString(dr1[4]);​
            SendOffersBy_Email = SendOffersBy_Email + Convert.ToString(dr1[5]);​
        }​
        if (email == "na" || email == "na@na.co.uk" || email == "na@na.com" || email == "")​
        {
            //MessageBox.Show("Customer " + CustomerID + " does not have an email linked.");​
        }​
        else
        {
            if (SendOffersBy_Email == "yes" || SendOffersBy_Email == "Yes")​
            {    ​
                try​
                {    ​
                    SendEmail(i, email, name);​
                }​
                catch (Exception ex)​
                {    ​
                    MessageBox.Show(ex.ToString());​
                }​
            }​
            else​
            {   ​
                //MessageBox.Show("Customer " + CustomerID + " does not accept emails.");​
            }​
        }​
    }​
    MessageBox.Show("Emails sent.");​
}​​

private void SendEmail(int i, string email, string name)​
{    ​​
    try​
    {    ​
        MailMessage mail = new MailMessage();​
        SmtpClient SmtpServer = new SmtpClient("smtp.live.com");​
        mail.From = new MailAddress("myemail");​
        mail.To.Add(email);​
        mail.Subject = "PRICE DROP!! Have your iPhone repaired today.";​
        mail.Body = "Hi " + name + ",\n" + ​
            "Our iPhone 7 and iPhone 8 series screen prices have now dropped in price!" + ​
            " Reply to this email to have your iPhone booked in for repair today - the prices may go back up! " + ​
            " All of our repairs come with our 6 months warranty and we can come to you." + ​
            "\n\nKind regards,\n Your Mobile Phone & Tablet Repair Specialist." + ​
            "\n\nTel: \nWebsite: \nEmail: " + ​
            "\nFacebook: " + ​
            "\n\n\n Don't want to recieve offers anymore? Just reply to this email to let us know and we will take you off our mailing system."​;​​

        SmtpServer.Port = 587;​
        SmtpServer.Credentials = new System.Net.NetworkCredential("myemail", "mypassword");​
        SmtpServer.EnableSsl = true;​
        SmtpServer.Send(mail);​
        mail.Dispose();​
    }​
    catch (Exception ex)​
    {    ​
        MessageBox.Show(ex.ToString());​
    }​​
}

2 个答案:

答案 0 :(得分:3)

代码有明显的改进:

    for (int i = 40; i < 1425; i++)​ //40-1425 is customerID's
    {
        clsDBConnector dbConnector1 = new clsDBConnector();​
        OleDbDataReader dr1;​
        string sqlStr1;​
        dbConnector1.Connect();​ 
        ...
   }

此代码会在每次遇到问题时打开数据库,这会增加开销,并且您的防病毒软件可能每次都在检查文件。

我建议将连接移到循环之外(并关闭),这样它就会变成

clsDBConnector dbConnector1 = new clsDBConnector();​
OleDbDataReader dr1;​
string sqlStr1;​
dbConnector1.Connect();​
for (int i = 40; i < 1425; i++)​ //40-1425 is customerID's
{
   // process data
}
dbConnector1.Close();

答案 1 :(得分:1)

尝试一下:

将数据库检索移动到单独的功能中。

仅执行一个查询即可获取所有数据并放入一个结构中。

private void button6_Click_1(object sender, EventArgs e)
{
    DialogResult dialogResult = MessageBox.Show("Are you sure to send email to all customers?(check code)", "Warning", MessageBoxButtons.YesNo);​
    if (dialogResult == DialogResult.Yes)​
    {
        DoButtonTask();​
    }​
}​​
private class Customer
{
    public string CustomerID {get; set;}
    public string Name {get; set;}
    public string Email {get; set;}
    public string SendOffersBy_Email {get; set;}     
}
private List<Customer> getCustomers(string query)
{
    List<Customer> output = new List<Customer>();
    try​
    {        
        clsDBConnector dbConnector1 = new clsDBConnector();​
        OleDbDataReader dr1;​
        dbConnector1.Connect();​

        dr1 = dbConnector1.DoSQL(query);

        while (dr1.Read())
        {   
            Customer c = new Customer();
            c.CustomerID = Convert.ToString(dr1[0]);
            c.Name = dr1[2];
            c.Email = Convert.ToString(dr1[4]);​
            c.SendOffersBy_Email = Convert.ToString(dr1[5]);​
            output.Add(c);
        }​
    ​}
    catch (Exception ex)​
    {    ​
        MessageBox.Show(ex.ToString());​
    }​​
    finally
    {
        return output;
    }

}
private void DoButtonTask()
{
    int minCustomerID = 40;
    int maxCustomerID = 1425;
    string  sqlStr1 = "SELECT CustomerID, DateAdded, FullName, PhoneNumber, EmailAddress, SendOffersByEmail"​ +
        " FROM Customer WHERE CustomerID >= " + minCustomerID + " and CustomerID < " + maxCustomerID + ";" ;​

    List<Customer> aCustomers = getCustomers(sqlStr1);

    foreach (customer in aCustomers)
    {
        string email = customer.Email;
        if (email == "na" || email == "na@na.co.uk" || email == "na@na.com" || email == "")​
        {
            //MessageBox.Show("Customer " + customer.CustomerID + " does not have an email linked.");​
        }​
        else
        {
            if (customer.SendOffersBy_Email == "yes" || customer.SendOffersBy_Email == "Yes")​
            {    
  ​             SendEmail(i, email, customer.Name);​
            }​
            else​
            {   ​
                //MessageBox.Show("Customer " + CustomerID + " does not accept emails.");​
            }​
        }​
    }

    MessageBox.Show("Emails sent.");​
}​​

private void SendEmail(int i, string email, string name)​
{    ​​
    try​
    {    ​
        MailMessage mail = new MailMessage();​
        SmtpClient SmtpServer = new SmtpClient("smtp.live.com");​
        mail.From = new MailAddress("myemail");​
        mail.To.Add(email);​
        mail.Subject = "PRICE DROP!! Have your iPhone repaired today.";​
        mail.Body = "Hi " + name + ",\n" + ​
            "Our iPhone 7 and iPhone 8 series screen prices have now dropped in price!" + ​
            " Reply to this email to have your iPhone booked in for repair today - the prices may go back up! " + ​
            " All of our repairs come with our 6 months warranty and we can come to you." + ​
            "\n\nKind regards,\n Your Mobile Phone & Tablet Repair Specialist." + ​
            "\n\nTel: \nWebsite: \nEmail: " + ​
            "\nFacebook: " + ​
            "\n\n\n Don't want to recieve offers anymore? Just reply to this email to let us know and we will take you off our mailing system."​;​​

        SmtpServer.Port = 587;​
        SmtpServer.Credentials = new System.Net.NetworkCredential("myemail", "mypassword");​
        SmtpServer.EnableSsl = true;​
        SmtpServer.Send(mail);​
        mail.Dispose();​
    }​
    catch (Exception ex)​
    {    ​
        MessageBox.Show(ex.ToString());​
    }​​
}