小编Kaf*_*afi的帖子

如何从 Windows 服务访问 SQL 数据库?

我正在尝试为 Windows 10(64 位)开发一个 Windows 服务,它打算定期在本地 MS SQL Server(v.11)中插入记录。

它安装并运行成功,但没有插入任何记录。我尝试了 System.Timers.TimerSystem.Threading.Timer

我还尝试在服务启动事件上插入。但这也不起作用。

这是我的代码:

public partial class Service1 : ServiceBase
{
    // System.Timers.Timer timer;
    System.Threading.Timer threadTimer;
   
    public Service1()
    {
        InitializeComponent();
    }


    //UPDATE: I checked the following method code in a console application. It works fine.
    private void InsertRecord()
    {
        try
        {
            using (SqlConnection connection = new SqlConnection("Server=.;Database=TestDb; Trusted_Connection=True;"))
            {
                using (SqlCommand command = new SqlCommand())
                {
                    command.Connection = connection;
                    command.CommandText = "Insert into .....')";
                    connection.Open();
                    command.ExecuteNonQuery();
                    connection.Close();
                } …
Run Code Online (Sandbox Code Playgroud)

c# sql-server windows-services windows-10

5
推荐指数
1
解决办法
6535
查看次数

标签 统计

c# ×1

sql-server ×1

windows-10 ×1

windows-services ×1