开发windows service完成SQL数据库的定时自动导出工作(ACCESS)

 using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Timers;
using System.Data.SqlClient;
using System.Net.Mail;

namespace BakupOnTime
{
    public partial class BackUpOnTime : ServiceBase
    {
        string[] tbNameArry;

        public BackUpOnTime()
        {
            InitializeComponent();

            if (!EventLog.SourceExists("MySource"))
            {
                EventLog.CreateEventSource("MySource", "Mylog");
            }

            eventLog1.Source = "MySource";

            eventLog1.Log = "Mylog";           
        }

        private string[] initTableNameArray()
        {
            string sqlCmdStr = "select name from sysobjects where xtype = 'U' and name!='dtproperties'";

            SqlConnection sqlCon = new SqlConnection("Data Source=localhost;Initial Catalog=infopublic;Persist Security Info=True;User ID=sa;Password=xxxxx);

            SqlCommand sqlCmd = new SqlCommand(sqlCmdStr, sqlCon);

            SqlDataReader sqlDr;

            sqlCon.Open();

            try
            {
                sqlDr = sqlCmd.ExecuteReader();

                string[] tbNameArray = new string[16];

                for (int i = 0; i < 16; i++)
                {
                    sqlDr.Read();

                    tbNameArray[i] = sqlDr[0].ToString();
                }

                return tbNameArray;
            }
            catch (SqlException ex)
            {
                eventLog1.WriteEntry(DateTime.Now.ToShortDateString() + ": " + ex.ToString());

                return null;
            }
        }

        private void sendMsg(string subject, string body)
        {
            try
            {
                SmtpClient client = new SmtpClient("邮件smtp服务器", 25);

                client.Credentials = new System.Net.NetworkCredential("qq号", "qq密码");

                MailMessage msg = new MailMessage("发件箱地址", "收件箱地址");

                msg.SubjectEncoding = System.Text.Encoding.UTF8;

                msg.BodyEncoding = System.Text.Encoding.UTF8;

                msg.Subject = subject;

                msg.Body = body;

                client.Send(msg);

                msg.Dispose();
            }
            catch (Exception ex)
            {
                eventLog1.WriteEntry(DateTime.Now.ToShortDateString() + ": " + ex.ToString());
            }
        }

        protected override void OnStart(string[] args)
        {
            tbNameArry = initTableNameArray();

            timer1.Enabled = true;
       }

        protected override void OnStop()
        {
            timer1.Enabled = false;
        }

        private void timer1_Elapsed(object sender, ElapsedEventArgs e)
        {
            timer1.Enabled = false;

            string dayofweek = DateTime.Now.DayOfWeek.ToString();

            string dir = @"d:/"; //导出后的access文件存放地址

            string sourceFileName = dir + "data.mdb";

            string destinationFileName = dir + DateTime.Now.ToShortDateString() + ".mdb";

            string msgBody = "";

            int recordsCount = 0;

            //检查导出时间

            if (dayofweek == "Friday" & DateTime.Now.Hour >= 17)
            {
                Console.WriteLine(DateTime.Now.ToShortDateString() + " " + DateTime.Now.DayOfWeek.ToString() + "/n");

                ((Timer)sender).Interval = 1000 * 60 * 60 * 24 * 7;

                Process copyProcess = new Process();

                ProcessStartInfo copyProcessStarInfor = new ProcessStartInfo("cmd.exe");

                copyProcessStarInfor.Arguments = "/c copy " + sourceFileName + " " + destinationFileName;

                copyProcess.StartInfo = copyProcessStarInfor;

                copyProcess.Start();

                while (!System.IO.File.Exists(destinationFileName))
                {
                    System.Threading.Thread.Sleep(2000);
                }

                SqlConnection sqlCon = new SqlConnection("Data Source=localhost;Initial Catalog=infopublic;Persist Security Info=True;User ID=sa;Password=xxzx6889;Asynchronous Processing=true");

                SqlCommand sqlCmd = new SqlCommand();

                sqlCmd.CommandTimeout = 600000;

                try
                {
                    sqlCon.Open();
                }
                catch (Exception ex)
                {
                    eventLog1.WriteEntry(ex.ToString());
                }

                try
                {
                    for (int i = 0; i < 16; i++)
                    {
                        string tabName = tbNameArry[i];

                        string sqlCmdStr = "insert into OpenRowSet('Microsoft.Jet.OLEDB.4.0','" + destinationFileName + "';'Admin';'','select * from " + tabName + "') select * from " + tabName + "";

                        sqlCmd.CommandText = sqlCmdStr;

                        sqlCmd.Connection = sqlCon;

                        IAsyncResult result = sqlCmd.BeginExecuteNonQuery();

                        while (!result.IsCompleted)
                        {
                            System.Threading.Thread.Sleep(20000);
                        }

                        recordsCount = sqlCmd.EndExecuteNonQuery(result);

                        msgBody = msgBody + "/n" + tabName + ": " + recordsCount + " Records";
                    }

                    eventLog1.WriteEntry(DateTime.Now.ToShortDateString() + ": " + msgBody);

                    sendMsg("Notice about the success of data transfer", msgBody);
                }
                catch (Exception ex)
                {
                    eventLog1.WriteEntry(DateTime.Now.ToShortDateString() + ": " + ex.ToString());

                    ((Timer)sender).Enabled = false;

                    sendMsg("Error Notice", ex.ToString());
                }
            }

            //根据当前时间,重新设置interval,以降低timer的运行次数
            else if (dayofweek == "Friday" & DateTime.Now.Hour <= 17)
            {
                if (DateTime.Now.Minute <= 10)
                {
                    ((Timer)sender).Interval = 1000 * 60 * 60;
                }
                else
                {
                    ((Timer)sender).Interval = 1000 * 60 * 10;
                }
            }
            else if (dayofweek != "Friday" & DateTime.Now.Hour <= 17)
            {
                ((Timer)sender).Interval = 1000 * 60 * 60 * 24;
            }
            else if (dayofweek != "Friday" & DateTime.Now.Hour >= 17)
            {
                ((Timer)sender).Interval = 1000 * 60 * 60;
            }

            timer1.Enabled = true;
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值