It is a follow-up question to my previous question in the same forum.
I would like to take a backup of my SQL Server database. Here is the code, for the backup in C#.
userConn = new SqlConnection(userdatabase);
userConn.Open();
string UserString;
UserString = "BACKUP DATABASE #DBName TO DISK = #FilePath";
String destPath = DestDirectory + "\\UserDataTable.bak";
SqlCommand cmd = new SqlCommand(UserString, userConn);
cmd.Parameters.AddWithValue("#dbName", userConn.Database);
cmd.Parameters.AddWithValue("#FilePath", destPath);
cmd.ExecuteNonQuery();
cmd.Dispose();
However, it throws an SQLException,
"Cannot open backup device
'D:\BookKeeping\Database\11_01_2013_21_15\Database\UserDataTable.bak'.
Operating system error 3(failed to retrieve text for this error.
Reason: 15105). BACKUP DATABASE is terminating abnormally."
Any Idea, what could be wrong ?
Thanks a lot for your time and your help.
"Operating system error 3" means that the directory was not found. SQL will not create the backup directory for you; you have to manually create it before running the backup command.
Make sure your SqlServer and the location where you want to create a backup is the same system. If you are using sqlServer remotely(Not located in your system) then you can not create a backup in your machine or you can not restore the database taking a .bak from your machine also.
Related
I have a database on the server shared on the local network. I would like to write an application that backs up the database from this server, but not on the server, but on the computer from which I started this application. That is, for a better understanding:
The database is on some Windows Server server. I have a laptop that is connected to the same network and has access to a database. On this laptop, I start the app, connect to the database and the .bak file is saved to the laptop, not the server.
At the moment I wrote only so much and unfortunately it doesn't work for me:
private static void CreateDatabaseBackup(string connectionString, string databaseName, string backupFilePath)
{
SqlConnection connection = new SqlConnection(connectionString);
SqlCommand backupCommand = connection.CreateCommand();
backupCommand.CommandText = $"BACKUP DATABASE {databaseName} TO DISK = '{backupFilePath}'";
connection.Open();
backupCommand.ExecuteNonQuery();
connection.Close();
}
This throws me an exception:
System.Data.SqlClient.SqlException: „Cannot open backup device 'C:\Backup\backup.bak'. Operating system error 3(The system cannot find the path specified.).
BACKUP DATABASE is terminating abnormally.”
Probably because of the fact that it is trying to save the file to the server's disk, and it does not have the path specified in the variable backupFilePath
I would like .bak to be saved to the disk of the device firing the application.
How to approach this problem?
I want to backup my remote SQL Server database onto the local computer.
So far I've tried:
using (SqlConnection defaultSqlConnection = new SqlConnection(Constants.Database_Constants.GetConnectionStringFromProfile(Constants.Profiles.Staging)))
{
string pathDatabase = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "\\backup_production_database"+DateTime.UtcNow.ToString("d_MMM_yyyy_HH_mm_ss", CultureInfo.InvariantCulture)+".bak";
WriteLine("The backup will be stored in " + pathDatabase);
string backupDb = "BACKUP DATABASE DB_Staging TO DISK = '" + pathDatabase+ "' WITH INIT, COMPRESSION";
File.Create(pathDatabase);
using (SqlCommand backupCommand = new SqlCommand(backupDb, defaultSqlConnection))
{
defaultSqlConnection.Open();
backupCommand.ExecuteNonQuery();
}
}
But I get this error :
Cannot open backup device 'XXXX\bin\Debug\backup_production_database22_Mar_2017_08_04_42.bak'.
Operating system error 3(The system cannot find the path specified.).
BACKUP DATABASE is terminating abnormally.
I know that I could generate a script using SQL Server Management Studio but it doesn't help me. I want to backup my database in a powershell script automatically without having to go manually into SQL Server Management Studio
You cannot create a directly backup from a remote server to a local disk.
Please look this link.
I am trying to restore a database backup file (.bak) to a newly created database using C#. I get the following inner exception:
Cannot open backup device '\GC.bak'. Operating system error 5 (Access is denied.).
RESTORE DATABASE is terminating abnormally
My server is a localDB.
void RestoreDB(string name)
{
var connection = new ServerConnection(Properties.Settings.Default.Well);
var sqlServer = new Server(connection);
var rstDatabase = new Restore();
rstDatabase.Database = name;
rstDatabase.Action = RestoreActionType.Database;
rstDatabase.Devices.AddDevice(AppDomain.CurrentDomain.BaseDirectory + "GC.bak", DeviceType.File);
rstDatabase.ReplaceDatabase = true;
rstDatabase.SqlRestore(sqlServer);
}
By default SQL Server only has access to a few specific places on the server drive (i.e. the default database and backup folder locations). It looks like you are probably trying to restore the file from a non-standard location, so you either need to grant permissions to the service account that SQL server is running under to that directory, or even easier, copy the backup file into the regular backup file location and try again.
I'm fight with a strange error occurs a couple of day ago and I'm not able to find a solution.
I have a C# Form application that talks with a SQL database made by Visual Studio Express (.mdf file). Everything works fine if my connection string points to the database in the root directory (where the DB has been automatically created by VS). I can compile the executable in Debug and Release.
To do a test in a different machine (where I copied the executable file and the database .mdf)I have changed the connection string in order to point to the database in the same executable directory and, in this case, it doesn't work (both release and debug).
I come to my PC and I use the same connection string above pointing not to the DB in the root directory bu to DB in Release directory.
The strange thing is that it works in debug but not in release.
The error occurs is the following one
Exception: One or more files do not match the primary file of the
database. If you are attempting to attach a database, retry the
operation with the correct files. If this is an existing database,
the file may be corrupted and should be restored from a backup. Could
not open new database 'C:\USERS\TEST\VISUAL
STUDIO\PROJECTS\LEONARDO\LEONARDO
0.1.1.1\LEONARDO\BIN\RELEASE\DB.MDF'. CREATE DATABASE is aborted. An attempt to attach an auto-named database for file C:\Users\Test\Visual
Studio\Projects\Leonardo\Leonardo 0.1.1.1\Leonardo\bin\Release\DB.mdf
failed. A database with the same name exists, or specified file cannot
be opened, or it is located on UNC share. Log file
'C:\Users\Test\Visual Studio\Projects\Leonardo\Leonardo
0.1.1.1\Leonardo\bin\Release\DB.ldf' does not match the primary file. It may be from a different database or the log may have been rebuilt
previously.
and the code is
string Result = string.Empty;
SqlConnection conn = new SqlConnection(Settings.DataBasePath);
try
{
conn.Open();
}
catch (Exception ex)
{
string Errore = String.Format("Exception: {0}", ex.Message);
MessageBox.Show(Errore);
throw;
}
SqlDataReader leggi = null;
//SqlCommand comando = new SqlCommand("SELECT " + "Database Version" + " FROM Data", conn);
SqlCommand comando = new SqlCommand("SELECT * FROM Data", conn);
leggi = comando.ExecuteReader();
while (leggi.Read())
{
Result += leggi["Database Version"].ToString().TrimEnd();
}
conn.Close();
Best regards
Your problem is here:
Log file 'C:\Users\Test\Visual Studio\Projects\Leonardo\Leonardo 0.1.1.1\Leonardo\bin\Release\DB.ldf' does not match the primary file.
You should make sure your debug and release folders contain the same .mdf and .ldf files.
My C#.Net windows Application connects to a SQLServer2005 database and implements database backup functionality.
In my Application,
I try to perform a file copy like this:
<!-- language:lang-csharp -->
File.Copy(Application.StartupPath + "\\dbSTK.mdf", "D:\\dbSTK123.mdf",true);
but it throws an exception with the following message:
" The Process cannot Access the File, because it is being use by another Process"
How can I copy the db file which is already in use?
You cannot copy mdf file while SqlServer is running. Just temporary shut SqlServer down or Detach that database (here) before copying.
Rather that copy the actual MDF, it's probably a better idea to backup the MDF using SQL Server's built in BACKUP command.
The suggestions to detach the database and then copy it are problematic because it takes your database offline.
The server denies inteprocess access to data files. Once it has opened a data file no other process can open one too. That's why your function fails.
You should close all open connections to DB to access the DB file. But generally, you should not touch the database file. You'd better use SQL command to back up the database.
string backupCommandText = "BACKUP DATABASE [<YOUR_DB_NAME>]" +
"TO DISK = N'<BACKUP_PATH>' WITH NOFORMAT, NOINIT, " +
"NAME = N'Web-Full Database Backup', SKIP, NOREWIND, NOUNLOAD, STATS = 10";
SqlCommand cmd = new SqlCommand();
cmd.CommandText = backupCommandText ;
cmd.Connection = conn;
cmd.ExecuteNonQuery();