我想通过恢复一个空数据库而不是通过 SQL 创建数据库来减少在本地计算机上创建数据库的工作量。
这是我到目前为止的代码(DataAccess.ApplicationDirectory 是“C:\ProgramData\RC Vehicle Management\”):
public static void CreateLocalDatabase () {
const String emptyDatabaseFileName = "EmptyDatabase.bak";
if(Directory.Exists(DataAccess.ApplicationDirectory) == false) {
Directory.CreateDirectory(DataAccess.ApplicationDirectory);
}
File.WriteAllBytes(Path.Combine(DataAccess.ApplicationDirectory + emptyDatabaseFileName), Resources.RcVehicleManagement);
using (SqlConnection sqlConnection = DataAccess.LocalMachineConnection()) {
sqlConnection.Open();
using (SqlCommand sqlCommand = new SqlCommand("RESTORE DATABASE [@localDatabaseName] " +
"FROM DISK = '@emptyDatabasePath' " +
"WITH NOUNLOAD, REPLACE", sqlConnection)) {
sqlCommand.Parameters.Add("@localDatabaseName", System.Data.SqlDbType.VarChar).Value = DataAccess.LocalDatabaseConnectionString.InitialCatalog;
sqlCommand.Parameters.Add("@emptyDatabasePath", System.Data.SqlDbType.VarChar).Value = Path.Combine(DataAccess.ApplicationDirectory, emptyDatabaseFileName);
sqlCommand.ExecuteNonQuery();
}
}
}
但是在执行时,我得到以下异常(在“sqlCommand.ExecuteNonQuery();”处):
Cannot open backup device 'c:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\Backup\@emptyDatabasePath'.
Operating system error 2(failed to retrieve text for this error. Reason: 15105).
RESTORE DATABASE is terminating abnormally.
我不知道它为什么要从“c:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\Backup”获取备份,我声明的路径是“C:\ProgramData\RC Vehicle Management\EmptyDatabase.巴克
我做错了什么?还是无法从“c:\Program Files\Microsoft SQL...\Backup”以外的路径恢复?