写windows服务日志-.net4.5.2-定时修改数据库中某些参数

环境:

windows 11

Visual Studio 2015

.net 4.5.2

SQL Server

目的:

定时修改数据库中某些参数的值

c 复制代码
定时修改24小时内,SQL数据库中,表JD_Reports 内,如果部门是'体检科',设置打印类型为 1
可以打印。

步骤:

1、新建项目,创建windows 服务

2、下载日志程序包 NLog

3、在App.config中配置日志包NLog

csharp 复制代码
<?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

csharp 复制代码
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、安装程序

csharp 复制代码
sc create Report_Print binPath= "E:\vs2015\study\Report_print\Report_print\bin\Debug\Report_print.exe"
sc start Report_Print 

9.1卸载程序

csharp 复制代码
sc stop Report_Print
sc delete Report_Print

10、安装成功

相关推荐
jiaoxingk4 分钟前
有关爬虫中数据库的封装——单线程爬虫
数据库·爬虫·python·mysql
ZXF-BW17 分钟前
联想笔记本电脑在Windows下通过联想驱动实现风扇控制
windows·电脑·联想·风扇
CHQIUU42 分钟前
在 C# .NET 中驾驭 JSON:使用 Newtonsoft.Json 进行解析与 POST 请求实战
c#·json·.net
JustLorain1 小时前
如何实现事务的可串行化快照隔离
数据库·后端·架构
星途码客1 小时前
SQL 易混易错知识点笔记1(drop,role,%,localhost)
数据库·sql·oracle
MXsoft6181 小时前
监控易一体化运维:巧用排班管理,提升运维协同效能
大数据·服务器·数据库
o0向阳而生0o1 小时前
27、Session有什么重⼤BUG?微软提出了什么⽅法加以解决?
c#·.net
Ant?12 小时前
rk3588 驱动开发(三)第五章 新字符设备驱动实验
数据库·驱动开发
Always_away2 小时前
数据库系统概论|第三章:关系数据库标准语言SQL—课程笔记6
数据库·笔记·sql·学习
csdn_aspnet2 小时前
如何在 Windows 10 中使用 WSL 和 Debian 安装 Postgresql 和 Postgis
windows·postgresql·debian