无法打开登录请求的数据库 "dbTest"。登录失败。 windows 服务

Cannot open database "dbTest" requested by the login. The login failed. windows service

我创建了一个 Windows 服务,它在固定时间间隔内进行 SQL 服务器数据库备份。 Windows 服务在调试模式下工作完美,但在安装时它保持 运行 但不创建 .bak 文件。

我检查了日志文件并找到了

Cannot open database "dbTest" requested by the login. The login failed.

我为连接使用了 Windows 身份验证。

这是我的代码片段

public partial class Service1 : ServiceBase
{
    Timer _timer = new Timer();

    public Service1()
    {
        InitializeComponent();
    }

    protected override void OnStart(string[] args)
    {
        this.WriteToFile("Simple Service started {0}");
        // _timer = new Timer(10 * 60 * 1000); // every 10 minutes
        _timer = new Timer(60000); // every 10 minutes
        _timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
        _timer.Start(); // <- important

    }

    private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    {
        this.WriteToFile("ScheduleBackupService: Method Call");
        this.ScheduleBackupService();
    }

    public void ScheduleBackupService()
    {
        string backupPath = ConfigurationManager.AppSettings["BackupFile"];
        this.WriteToFile("Backup Path {0}" + backupPath);
        string ConnectionString = ConfigurationManager.AppSettings["ConnectionString"];
        this.WriteToFile("Connection String {0}" + ConnectionString);
        string DbList = ConfigurationManager.AppSettings["dbList"];
        this.WriteToFile("Connection String {0}" + DbList);
        string[] words = DbList.Split(',');
        foreach (string word in words)
        {
            //Console.WriteLine("WORD: " + word);
            CreateBackFile(backupPath, word, ConnectionString);
        }


    }
    internal static string CreateDirectory(string path)
    {
        if (!Directory.Exists(path))
        {
            Directory.CreateDirectory(path);
        }
        return path;
    }
    public string GetDirectoryPath()
    {

        string filePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "SqlDataBaseBackup");

        if (!Directory.Exists(filePath))
        {
            Directory.CreateDirectory(filePath);
        }
        return filePath;

    }

    public void CreateBackFile(string path, string dbName, string ConnectionString)
    {
        try
        {
            string name = dbName;            
            name = name + ".bak";
            string backupPath = @"BACKUP DATABASE " + dbName + " TO DISK = N'" + path + @"\" + name + @"'";
            this.WriteToFile("backup Path Query" + backupPath);
            string svr = ConnectionString;
            SqlConnection con = new SqlConnection(svr);
            SqlCommand cmd = new SqlCommand(backupPath, con);
            try
            {
                con.Open();
                cmd.ExecuteNonQuery();
                this.WriteToFile("BackUp Create Successfully {0}" + dbName);                
            }

            catch (Exception ex)
            {
                WriteToFile("Service Error Exception CreateBackFile: {0} " + ex.Message);
                this.WriteToFile("Service Error Exception CreateBackFile" + ex.StackTrace);                
            }

            finally
            {
                if (con.State == ConnectionState.Open)
                {
                    con.Close();
                }
            }
        }
        catch (Exception ex)
        {

            this.WriteToFile("Service Error Exception : {0} " + ex.Message);
            this.WriteToFile("Service Error Exception  : {0}" + ex.StackTrace);
            //Stop the Windows Service.
            using (System.ServiceProcess.ServiceController serviceController = new System.ServiceProcess.ServiceController("Service1"))
            {
                serviceController.Stop();
            }
        }

    }

    private void CreateZipFile(string path, string dbName)
    {
        //to store the value of folderapth   
        string FolderPathToZip = path;
        //To create unique file name with date and time with nanoseconds.  

        string ZbackupPath = CreateDirectory(GetDirectoryPath() + "\BackupZip\");
        string ZipFileName = ZbackupPath + dbName + ".zip";
        try
        {
            if (System.IO.File.Exists(ZipFileName))
                System.IO.File.Delete(ZipFileName);
            ZipFile.CreateFromDirectory(FolderPathToZip, ZipFileName);
            Array.ForEach(Directory.GetFiles(path), File.Delete);
            this.WriteToFile("File Copy  Successfully {0} this" + path);
        }
        catch (Exception ex)
        {
            //If system throw any exception message box will display "SOME ERROR"  
            // Notification(ex.Message);
        }

    }

    public void WriteToFile(string text)
    {
        string path = ConfigurationManager.AppSettings["LogFile"];
        using (StreamWriter writer = new StreamWriter(path, true))
        {
            writer.WriteLine(string.Format(text, DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt")));
            writer.Close();
        }
    }
    protected override void OnStop()
    {
        this.WriteToFile("Simple Service stopped {0}");        
    }
}

这是我保存在 app.config 中的连接字符串:

<appSettings>
    <add key ="Mode" value ="Interval"/>        
    <add key ="ConnectionString" value ="Data Source=DESKTOP-2TGRDDE;Initial Catalog=dbTest;Integrated Security=True"/>    
    <add key ="dbList" value ="dbBackUpFtp"/>
    <add key ="LogFile" value ="D:\Backup\ServiceLog.txt"/>
    <add key ="BackupFile" value ="D:\Backup\"/>
    <add key ="IntervalMinutes" value ="1"/>
    <add key ="ScheduledTime" value ="16:02"/>
  </appSettings>

和初始化中的项目安装程序内容

private void InitializeComponent()
{
    this.serviceProcessInstaller1 = new System.ServiceProcess.ServiceProcessInstaller();
    this.serviceInstaller1 = new System.ServiceProcess.ServiceInstaller();
    // 
    // serviceProcessInstaller1
    // 
    this.serviceProcessInstaller1.Account = System.ServiceProcess.ServiceAccount.LocalSystem;
    this.serviceProcessInstaller1.Password = null;
    this.serviceProcessInstaller1.Username = null;
    // 
    // serviceInstaller1
    // 

    this.serviceInstaller1.Description = "BackUp Service";
    this.serviceInstaller1.DisplayName = "BackUpService.Demo";
    this.serviceInstaller1.ServiceName = "Service1";
    // 
    // ProjectInstaller
    // 
    this.Installers.AddRange(new System.Configuration.Install.Installer[] {
    this.serviceProcessInstaller1,
    this.serviceInstaller1});

}

抱歉,我上传了所有代码和很多研发但失败了。

是否需要对代码部分进行任何更改

由于服务帐户是 LocalSystem,该帐户需要连接到 dbTest 数据库的权限以及备份数据库的权限。假设服务和 SQL 服务器在同一台机器上 运行,分配最小权限以备份数据库的脚本是:

USE dbTest;
CREATE USER [NT AUTHORITY\SYSTEM];
ALTER ROLE db_backupoperator
    ADD MEMBER [NT AUTHORITY\SYSTEM];