Error in C# Code Backup option - c#

I have wrote this code
but its generating error
please help
System.IO.File.Copy("JDB.mdf", "d:\\JDB.mdf", true);
System.IO.File.Copy("JDb_log.ldf", "d:\\JDb_log.ldf", true);
the error is
The process cannot access the file 'JDB.mdf' because it is being used by another process.
Please help me

The file is being used by some process. I believe the database is still attached to Sql Server.
Use Process Explorer tool from Sys Internal to find out the program using this file.
Why don't you use SQL back tool to backup the database?
Check out What happens during a live SQL Server backup?
If you still want to backup or make copy of ldf mdf files then you can perform these steps:
1. Detach database
USE MASTER;
GO
-- Take database in single user mode -- if you are facing errors
-- This may terminate your active transactions for database
ALTER DATABASE DatabaseName
SET SINGLE_USER
WITH ROLLBACK IMMEDIATE;
GO
-- Detach DB
EXEC MASTER.dbo.sp_detach_db #dbname = N'DatabaseName'
Open Windows Explorer go to the the folder where ldf and mdf files are and then copy the file manually.
Reattach the database:
USE [master]
GO
CREATE DATABASE [DatabaseName] ON
( FILENAME = N’C:\Data\DataBase_Data.mdf’ ),
( FILENAME = N’C:\Data\Database_Log.ldf’ )
FOR ATTACH
GO
IF EXISTS ( SELECT name FROM master.sys.databases sd
WHERE name = N’DataBaseName’ AND SUSER_SNAME(sd.owner_sid) = SUSER_SNAME() )
EXEC [AdventureWorks].dbo.sp_changedbowner #loginame=N’sa’,#map=false
If you want to do it programatically, then you can execute the command given in step 1,2,3 using ADO.NET and the use c# file copy command to copy the file.

Download Process Explorer and run the program.
Option 1:
Click the Find menu, and choose Find Handle or DLL...
Type the file name (in your case JDB.mdf)
After typing the search phrase, click the Search button
Once you know what process the file has locked you, need to close that process (by closing that program). Another option is to use KILL in the process explorer terminating that process.
Option 2:
From the error message, the .mdf file has already been attached to an instance of an SQL Server. If you have multiple instances running, make sure it is detached from any other instance.

Related

How do I disconnect open connections to an Azure SQL Managed Instance?

I am working on a process for restoring a database to my Azure SQL Managed instance which involves dropping the existing database and restoring a backup in its place (since Managed Instance doesn't support WITH REPLACE).
I am, however, running into an issue with disconnecting any open connections so I can do this operation. Users should be warned before updates take place, but we cannot guarantee no open connections.
Typically, I would do something along the lines of the following:
ALTER DATABASE AdventureWorks2012 SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
--RESTORE HERE
ALTER DATABASE AdventureWorks2012 SET MULTI_USER;
When I attempt to run something like this against the database in the managed instance, however, I get the following error:
This ALTER DATABASE statement is not supported. Correct the syntax and execute the statement again. ALTER DATABASE statement failed.
Is there a way to accomplish this in an Azure SQL Managed Instance?
In RESTORE FROM URL in Managed Instance you can't even replace existing databases.
So either drop or rename the database before the RESTORE. Both DROP DATABASE MyDb and ALTER DATABASE MyDb MODIFY NAME = MyDb_old will kill existing connections to the database.
Alternatively you can use the Managed Point-in-Time Restore to restore an existing database to a previous point-in-time.

SQL Server User Instances error: Existing databases has reached the max number allowed

I'm using C# in Visual Studio 2008 to loop through MDF Files on my PC and extract data from within them. I'm using a Table Adapter to point to the local MDF file.
Recently one of my PC's refuses to let me attach any new Data Source as it says
System.Data.SqlClient.SqlException: Unable to create/attach any new database because the number of existing databases has reached the
maximum number allowed: 32766
Even if I start a fresh Windows application and try to add an MDF file (on my desktop) to it as a Data Source, I get the above error.
Can anyone tell me how to remove/delete the existing connections ?
My code works fine on another PC and I've re-installed Visual Studio on my PC but still get this error.
C# Table adapter code:
tmTableAdapter.Connection.ConnectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename='" + pathofmdffile + "';Integrated Security=True;Connect Timeout=30;User Instance=True";
tmTableAdapter.Connection.Open();
Reinstalling VS won't help as the error is coming from SQL Server.
Look at these MSDN pages which have lots of good info:
SQL Server Express User Instances
SQL Server 2005 Express Edition User Instances
User Instances for Non-Administrators
Since you are using "User Instances", I guess the DBs won't show up when connecting to the main SQLEXPRESS instance.
Things to check:
In SSMS, connect to your last attached DB by doing the following:
Go to Object Explorer
New Connection to a Database Engine
In the "Connect to Server" popup:
Click the "Options >>" button
Go to the "Additional Connection Properties" tab
Enter in the following in the text area:
User Instance = true
Click the "Connect" button
Expand "Databases" folder. You should see them all, named as the full path to the MDF file
Right-click on a database
Go to "Tasks >"
First option is "Detach"
Obviously this isn't practical for 32,766 databases, but for a few it is the best option.
By default the sqlservr.exe process hangs around for 60 minutes, and any databases you attach prior to it terminating gets added to the list and likely reset the expiration counter. You can end the process immediately by connecting to the most recent attached DB (as noted above; those steps will work for a New Query, or if connecting via Object Explorer, then right-click on the instance name and go to "New Query"), and run the following:
SHUTDOWN;
This will clear out all connected databases in one shot.
Set the timeout to be less than 60 minutes. According to the SQL Server Express User Instances page (same link as above):
A system administrator on the parent instance can set the duration of the time-out period for a user instance by using sp_configure to change the user instance timeout option. The default is 60 minutes.
In SSMS (make sure you are connected to the parent instance):
-- View current setting (in the "run_value" field)
EXEC sp_configure 'user instance timeout'
-- Documentation says default is 60 but mine was 5
-- If you can't see the option, run the following:
EXEC sp_configure 'show advanced options', 1;
RECONFIGURE;
-- To change it, run the following:
EXEC sp_configure 'user instance timeout', 5;
Use the "SQL Server Express Utility" to detach one or more databases:
SSEUtil.exe was written in 2005 and has not been updated since (current version is v1.0.2130)
Download from: https://www.microsoft.com/en-us/download/confirmation.aspx?id=3990
Use the -d[etach] <dbpath[*]>|name=<dbname> command
Look in the following directory which will have the 4 system DBs:
On XP / Vista: C:\Documents and Settings{UserName}\Local Settings\Application Data\Microsoft\Microsoft SQL Server Data\SQLEXPRESS
On Windows 7 and newer: C:\Users{UserName}\AppData\Local\Microsoft\Microsoft SQL Server Data\SQLEXPRESS
This is mostly just informational as these files cannot be deleted so long as the SQL Server process is running.
For an on-going basis, if you will be attaching many DBs in a loop, you can programatically get rid of them in that process by running sp_detach_db when you are done using each DB:
USE [master];
ALTER DATABASE [{DatabaseName}] SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
EXEC sp_detach_db #dbname =N'{DatabaseName}';
And just FYI, "User Instances" are now deprecated. You should look into using SQL Server Express LocalDB.

Have Sql SMO Delete Database Backup File

I have create a C# application that allows a database to be backed up and restored. It does this by first backing the database up to a local file on the Sql server using:
Backup backup = new Backup();
backup.Devices.AddDevice(Path.GetFullPath(backupFilePath), DeviceType.File);
...
backup.SqlBackup(server);
And then I create the new database by restoring from the backup file using:
Restore restore = new Restore();
restore.Devices.AddDevice(Path.GetFullPath(backupFileToRestoreFrom), DeviceType.File);
...
restore.SqlRestore(server);
After the new database has been created I want to delete the temp backup file that we created. Because I have admin rights on the Sql server box, I can delete the file on the remote server using:
File.Delete("\\SqlServer\C$\Backups\BackupFileToDelete.bak")
and it works. However, if somebody else who doesn't have rights on the Sql server box runs the app, it will throw an exception about not having permissions.
So is there a Sql SMO function that I can call to delete the backup file that was created on the remote Sql server?
If you delete the file using the xp_cmdshell then it will use the rights of the sql server instead of the rights of the person.
For example:
EXEC master..xp_cmdshell 'Del \\SqlServer\C$\Backups\BackupFileToDelete.bak', NO_OUTPUT
Here's the reference on xp_cmdshell
The important thing to note from that article is:
Because malicious users sometimes attempt to elevate their privileges
by using xp_cmdshell, xp_cmdshell is disabled by default. Use
sp_configure or Policy Based Management to enable it. For more
information, see xp_cmdshell Server Configuration Option.
Another possibility is to use SQLCLR, which is more secure than using xp_cmdshell. There's even a CodePlex project call SQLCLR File Functions that has the functionality written as stored procs for me. I think I'm going to see if I can convince our DBAs to go this route. The downside is that I believe the sprocs that this creates would need to be installed on every existing and new SQL Server that gets created; not much different than having to enable xp_cmdshell on every server though I guess.

Showing error while back up the database in sql server

I am facing some error while i am trying to back up my database in sql server R2.
it is showing the following error:
TITLE: Microsoft SQL Server Management Studio
Restore failed for Server 'Ironhide\SQLEXPRESS'. (Microsoft.SqlServer.SmoExtended)
ADDITIONAL INFORMATION:
System.Data.SqlClient.SqlError: The media set has 2 media families but only 1 are provided. All members must be provided. (Microsoft.SqlServer.Smo)
This i commonly a problem with how the database backup was taken, it looks like when the backup was created it was split into two files, you wont be able to restore it unless you have both those files. Try creating the backup again but when you do the backup insure that you only have one file in the destination section.
This question has been already asked in SO: Any other solutions for SQL's “The media set has 2 media families but only 1 are provided. All members must be provided.” error?
Anyway, your backup set was splitted in two files, but you're trying to restore the data from just only one backup file.
One solution is to backup your data in just one file and repeat the restore process. The other one is to provide both backup files and try to restore again the data. In this way, SQL Server won't warn you again with that error.
The Microsoft Project Manager for SQL Backup explains here the error.

Backup C# Windows application data

I'm designing a Windows application using C# in Visual Studio. I need to create back up button or something that would back up my data. How do I do that?
Simlpy create a back up for you data base. I should not be a big problem to triger that proces from your code.
check this sites:
How to Create Full Database Backup on MS SQL Server for a Database using T-SQL Backup Database command and SqlCmd Utility
How to: Create a Full Database Backup
Create a new store procedure similar to the content below and call it from your code.
Copy Code USE AdventureWorks2008R2;
GO
BACKUP DATABASE AdventureWorks2008R2
TO DISK = 'Z:\SQLServerBackups\AdventureWorks2008R2.Bak'
WITH FORMAT,
MEDIANAME = 'Z_SQLServerBackups',
NAME = 'Full Backup of AdventureWorks2008R2';
GO

Categories

Resources