现在的位置: 首页C#>正文
开发windows service完成SQL数据库的定时自动导出ACCESS
2009年03月13日 C# 暂无评论 ⁄ 被围观 阅读(1,279)+
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
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;
        }
    }
}

给我留言

留言无头像?


[face=9] [face=8] [face=7] [face=6] [face=5] [face=4] [face=3] [face=30] [face=2] [face=29] [face=28] [face=27] [face=26] [face=25] [face=24] [face=23] [face=22] [face=21] [face=20] [face=1] [face=19] [face=18] [face=17] [face=16] [face=15] [face=14] [face=13] [face=12] [face=11] [face=10] [em=9] [em=8] [em=7] [em=6] [em=5] [em=4] [em=3] [em=30] [em=2] [em=29] [em=28] [em=27] [em=26] [em=25] [em=24] [em=23] [em=22] [em=21] [em=20] [em=1] [em=19] [em=18] [em=17] [em=16] [em=15] [em=14] [em=13] [em=12] [em=11] [em=10] ;) :| :x :twisted: :roll: :oops: :o :mrgreen: :lol: :idea: :evil: :cry: :arrow: :P :D :?: :? :) :( :!: 8O 8)