環境:
windows 11
Visual Studio 2015
.net 4.5.2
SQL Server
目的:
定時修改數據庫中某些參數的值
定時修改24小時內,SQL數據庫中,表JD_Reports 內,如果部門是‘體檢科',設置打印類型為 1
可以打印。
步驟:
1、新建項目,創建windows 服務
2、下載日志程序包 NLog
3、在App.config中配置日志包NLog
<?xml version="1.0" encoding="utf-8" ?>
<configuration><configSections><section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog"/></configSections><nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><targets><target name="file" xsi:type="File" fileName="${basedir}/Logs/${date:format=yyyy-MM-dd}/${date:format=yyyy-MM-dd}.txt" layout="[${date:format=yyyy-MM-dd HH\:mm\:ss}][${level}] ${message} ${exception}"/></targets><rules><logger name="*" minlevel="Debug" writeTo="file"/></rules></nlog><startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" /></startup>
</configuration>
4、Report_Print.cs
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.Threading.Tasks;
using System.Data.SqlClient;
using System.Timers;
using NLog; // 引入 NLog 命名空間,用于日志記錄namespace Report_print
{public partial class Report_Print : ServiceBase{private Timer _timer;private readonly string _connectionString = "Data Source=.;Initial Catalog=【自己數據庫】;User Id=sa;Password=【自己的密碼】;";// 創建一個靜態日志記錄器實例,用于在服務中記錄日志private static readonly Logger Log = LogManager.GetCurrentClassLogger();public Report_Print(){InitializeComponent();// 設置服務每5分鐘檢查一次_timer = new Timer(5 * 60 * 1000); // 5分鐘_timer.Elapsed += TimerElapsed;}protected override void OnStart(string[] args){// 服務啟動時記錄日志Log.Debug("開始執行");_timer.Start();// 啟動時立即執行一次UpdatePrintType();}protected override void OnStop(){_timer.Stop();// 服務啟動時記錄日志Log.Debug("服務停止執行");}private void TimerElapsed(object sender, ElapsedEventArgs e){UpdatePrintType();}private void UpdatePrintType(){try{using (SqlConnection conn = new SqlConnection(_connectionString)){conn.Open();string sql = @"UPDATE JD_Reports SET PrintType = 1 WHERE Depart = '體檢科' AND CheckTime >= DATEADD(HOUR, -24, GETDATE())AND (PrintType IS NULL OR PrintType != 1)";using (SqlCommand cmd = new SqlCommand(sql, conn)){int rowsAffected = cmd.ExecuteNonQuery();Log.Debug("寫入日志成功: " + rowsAffected.ToString());// 這里可以添加日志記錄受影響的行數}}}catch (Exception ex){// 這里應該添加適當的錯誤日志記錄// 例如使用 EventLog 或其他日志框架}}}
}
5、在 Report_Print.cs 界面內,右鍵"添加安裝程序"
6、配置ServiceInstaller1
7、配置serviceProcessInstaller1
8、右鍵,編譯程序
完成
9、安裝程序
sc create Report_Print binPath= "E:\vs2015\study\Report_print\Report_print\bin\Debug\Report_print.exe"
sc start Report_Print
9.1卸載程序
sc stop Report_Print
sc delete Report_Print