我有一个简单的 Windows 应用程序,它使用 SQL Server 2014 LocalDB(.mdf
文件)。
我希望每当用户单击退出按钮时,我的应用程序会自动将其 localdb 文件 ( .mdf
) 备份到用户同一台计算机中的另一个文件夹中。
我在下面写了简单的代码,但是发生了 SQLException 语法错误:
'C:\greendb_angelheart.mdf' 附近的语法不正确
(DATABASE ""{0}""
语法看起来不错)
我担心localdb
使用普通SqlConnection
代码连接到特定文件是否正确。
我的简单代码是:
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
if (MessageBox.Show("Really want to exit? Thank you !", MessageBoxButton.YesNo, MessageBoxImage.Warning) == MessageBoxResult.No)
{
e.Cancel = true;
}
else
{
string backuppath_basic = @"c:\Green_Backup";
if (!System.IO.Directory.Exists("backuppath_basic"))
{
System.IO.Directory.CreateDirectory(backuppath_basic);
}
var greendbfileName = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), string.Format("greendb_{0}.mdf", personID));
var copied_greendbfileName = string.Format(@"C:\greendb_{0}.mdf", personID);
string localConnectionString = string.Format(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename= " + Environment.GetEnvironmentVariable("APPDATA") + @"\greendb_{0}.mdf;Integrated Security=True;Connect Timeout=30;", personID);
SqlConnection backupConn = new SqlConnection();
backupConn.ConnectionString = localConnectionString;
backupConn.Open();
SqlCommand backupcomm = backupConn.CreateCommand();
string backupdb = @"BACKUP DATABASE ""{0}"" TO DISK '{1}'";
backupdb = string.Format(backupdb, greendbfileName, copied_greendbfileName);
SqlCommand backupcreatecomm = new SqlCommand(backupdb, backupConn);
backupcreatecomm.ExecuteNonQuery();
backupConn.Close();
Environment.Exit(0);
}
}