I'm using following code to restore a BAK file to an MDF file, initially I create a database and then try to restore it using my BAK file, but I get some errors:
I use an open file dialog to select my BAK file
openDialogConvert.ShowDialog();
RegistryKey rk = Registry.LocalMachine.OpenSubKey(#"SOFTWARE\Microsoft\Microsoft SQL Server");
String[] instances = (String[])rk.GetValue("InstalledInstances");
string sqlname = "";
if (instances.Length > 0)
{
foreach (String element in instances)
{
if (element == "MSSQLSERVER")
sqlname = System.Environment.MachineName;
else
sqlname = System.Environment.MachineName + #"\" + element;
}
}
String str;
SqlConnection myConn = new SqlConnection("Server=" + sqlname + ";Integrated security=SSPI;database=master");
string dbname = "tmpDB" + DateTime.Now.Ticks.ToString();
str = "CREATE DATABASE " + dbname + " ON PRIMARY " +
"(NAME = MyDatabase_Data, " +
"FILENAME = '" + Environment.CurrentDirectory + "\\" + dbname + ".mdf') " +
"LOG ON (NAME = MyDatabase_Log, " +
"FILENAME = '" + Environment.CurrentDirectory + "\\" + dbname + ".ldf') ";
SqlCommand myCommand = new SqlCommand(str, myConn);
try
{
myConn.Open();
myCommand.ExecuteNonQuery();
MessageBox.Show("DataBase is Created Successfully", "MyProgram", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (System.Exception ex)
{
MessageBox.Show(ex.ToString(), "MyProgram", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
myCommand.Dispose();
str = #"RESTORE DATABASE [" + dbname + "] FROM DISK = N'" + openDialogConvert.FileName + #"' WITH MOVE N'IODB_Data'
TO N'" + Environment.CurrentDirectory + #"\\" + dbname + #".mdf', MOVE N'IODB_Log'
TO N'" + Environment.CurrentDirectory + #"\\" + dbname + #".ldf', REPLACE ";
myCommand = new SqlCommand(str, myConn);
myCommand.ExecuteNonQuery();
myCommand.Dispose();
myConn.Close();
my new (empty) database is created successfully but I get strange errors while trying to restore the BAK file in this newly created database.
I get following error using the above code:
The operating system returned the error '32(failed to retrieve text
for this error. Reason: 15105)' while attempting
'RestoreContainer::ValidateTargetForCreation' on 'D:\7 mordad
fara\Ofogh-Dsk\Ofogh-Dsk\bin\Debug\tmpDB635107927412887254.mdf'.
File 'IODB_Data' cannot be restored to 'D:\7 mordad
fara\Ofogh-Dsk\Ofogh-Dsk\bin\Debug\tmpDB635107927412887254.mdf'. Use
WITH MOVE to identify a valid location for the file.
The operating system returned the error '32(failed to retrieve text
for this error. Reason: 15105)' while attempting
'RestoreContainer::ValidateTargetForCreation' on 'D:\7 mordad
fara\Ofogh-Dsk\Ofogh-Dsk\bin\Debug\tmpDB635107927412887254.ldf'.
File 'IODB_Log' cannot be restored to 'D:\7 mordad
fara\Ofogh-Dsk\Ofogh-Dsk\bin\Debug\tmpDB635107927412887254.ldf'. Use
WITH MOVE to identify a valid location for the file.
Problems were identified while planning for the RESTORE statement. Previous messages provide details.
RESTORE DATABASE is terminating abnormally.
but when I insert a 'GO' at the end my command, I get following error:
Incorrect syntax near GO
what is going wrong here?
of course I've tested the restore operation successfully with SQL server management studio and I've found correct logical names for my BAK file (in fact I've copied the script from MSSMS)
You can also try this.
Step 1 - connect the database server using MS SQL Server Management
Studio.
step 2 - Find the database in the left pane & right-click to choose
the restore option.
Step 3 - Choose the destination and source for restoration.
Step 4 - Browse for the backup file from the device & click on ok
Step 5 - Select the database you want to restore from the list and
click ok.
After completing the restore process, your database will be ready to use.
Note: You must create a new database to restore the old one.
Related
While using MySQLConnection in C# trying to do a LOAD LOCAL DATA INFILE, how to resolve the error "The used command is not allowed with this MySQL version"
Full error is:
MySql.Data.MySqlClient.MySqlException HResult=0x80004005 Message=The used command is not allowed with this MySQL version
In the connection string, include AllowLoadLocalInfile=true;
Server also need to be set up to allow local load data infile
string connectionStr = "Server=" + server + "; Database=" + database + ";Uid=" + user + ";Pwd="+ pw + ";Port=" + port + "; CharSet=utf8;ConnectionTimeout=6000;DefaultCommandTimeout=6000;";
connectionStr += "AllowLoadLocalInfile=true;"; // Added on separate line for clarity
try
{
sourceConn = new MySqlConnection(connectionStr);
sourceConn.Open();
}
catch(Exception ex)
{
Console.WriteLine("Error opening db connection: " + ex.Message + " trace: " + ex.StackTrace);
}
Here's a list of connection options: https://mysqlconnector.net/connection-options/
I used Database first EF method to create a Model in a wpf application using C#. After adding relevant information, changing column's names, table's names, I want to copy it to a new location. But I get the error message that the database is in use.
using (var ctx = new TableGraphDBEntities())
{
for (int l = 0, m = 1; l < TableNames.Count; l++, m++)
{
string columnxQ = "sp_rename 'Table1.x','" + XNames[l] + "', 'COLUMN'";
string columnyQ = "sp_rename 'Table1.y','" + YNames[l] + "', 'COLUMN'";
string talbeQ = "sp_rename Table" + m.ToString() + "," + TableNames[l];
string detachQ = "sp_detach_db #dbname = N'TableGraphDB'";
//string setOffline = "
//string detachQ = "USE master; GO EXEC sp_detach_db #dbname = N'TableGraphDB'; GO";
ctx.Database.ExecuteSqlCommand(columnxQ);
ctx.Database.ExecuteSqlCommand(columnyQ);
ctx.Database.ExecuteSqlCommand(talbeQ);
ctx.Database.ExecuteSqlCommand(detachQ);
}
}
string oldFilePath = System.AppDomain.CurrentDomain.BaseDirectory + "TableGraphDB.mdf";
string FilePath = Properties.Settings.Default.ExtensionFileDir + #"\Saved DataBases\" + fnw.FileName + ".mdf";
if (File.Exists(FilePath))
{
MessageBox.Show("The database aleady exist, please type a different name");
return;
}
//FileInfo fileInfo = new FileInfo(oldFilePath);
//while (IsFileLocked(fileInfo))
//{
//}
File.Copy(oldFilePath, FilePath);
MessageBox.Show("Database is saved!");
Here is the link to slq command http://msdn.microsoft.com/en-gb/library/ms187858.aspx
The database is located in the Bin folder. It is copied as a new copy from the project each time I run the application. If I close the application and reopen it, it can be copied with all the data.
I tried using ExecuteSqlCommand(), but it didn't help. So how could I detach the database so that I could move/copy it?
Unfortunately StackOverFlow doesn't let me to answer my own question, so I have to write it down in here.
Answer:
First of all you have to check the actual name of your Database, it's not necessarily the name of the database file. In order to do that you need to:
Open the server explorer in Visual Studio or SQL Management Studio.
Open new query.
Execute the following query: SELECT name, create_date FROM sys.databases
Check the name of the database (in my case it was the full path of the database file, it can be only the name of the database or anything else.)
Then you can change the name of the columns and tables by executing the following code:
using (var ctx = new TableGraphDBEntities())
{
for (int l = 0, m = 1; l < TableNames.Count; l++, m++)
{
string columnxQ = "sp_rename 'Table1.x','" + XNames[l] + "', 'COLUMN'";
string columnyQ = "sp_rename 'Table1.y','" + YNames[l] + "', 'COLUMN'";
string talbeQ = "sp_rename Table" + m.ToString() + "," + TableNames[l];
ctx.Database.ExecuteSqlCommand(columnxQ);
ctx.Database.ExecuteSqlCommand(columnyQ);
ctx.Database.ExecuteSqlCommand(talbeQ);
ctx.Dispose();
}
}
And finally use the following code to detach and move it to a new location:
string oldFilePath = System.AppDomain.CurrentDomain.BaseDirectory + "TableGraphDB.mdf";
string conString = #"Data Source=(LocalDB)\v11.0;Integrated Security=True;";
using (System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection(conString))
{
string query = #"USE [master]
ALTER DATABASE ["+oldFilePath+#"] SET SINGLE_USER WITH ROLLBACK IMMEDIATE
USE [master]
EXEC master.dbo.sp_detach_db #dbname = N'"+oldFilePath+"'";
SqlCommand cmd = new SqlCommand(query, con);
con.Open();
cmd.ExecuteNonQuery();
cmd.Dispose();
con.Dispose();
}
string FilePath = Properties.Settings.Default.ExtensionFileDir + #"\Saved DataBases\" + fnw.FileName + ".mdf";
if (File.Exists(FilePath))
{
MessageBox.Show("The database aleady exist, please type a different name");
return;
}
File.Copy(oldFilePath, FilePath);
Note: If you try implement ctx.Database.ExecuteSqlCommand(query), you'll get the following error:
ALTER DATABASE statement not allowed within multi-statement transaction.
The procedure 'sys.sp_detach_db' cannot be executed within a transaction.
Changed database context to 'master'.
If you're using EF6 you may try this code:
string command = "EXEC sp_detach_db 'TableGraphDB', 'true'";
dbContext.ExecuteStoreCommand(command);
Second parameter in sp_detach_db procedure will drop all connections to this database
In SSMS this is the query that is used to detach a database.
Can you try this?
You should just be able to wrap the whole thing up as a string and execute it.
I'm not sure if it will be happy with the 'GO', so you might have to remove those.
string detachQ = "" +
"USE [master]\n" +
"GO\n" +
"ALTER DATABASE [TableGraphDB] SET SINGLE_USER WITH ROLLBACK IMMEDIATE\n" +
"GO\n" +
"USE [master]\n" +
"GO\n" +
"EXEC master.dbo.sp_detach_db #dbname = N'TableGraphDB'\n" +
"GO\n";
ctx.Database.ExecuteSqlCommand(detachQ);
I'm restoring a SQL Server .bak file on SQL Server Express. But after restoring the database, I cannot use it in my code, it seems that the file is somehow locked, and the only way is copying it to another folder, also when I try to copy the .mdf file (using Windows Explorer) I get a warning about admin permission. I cannot copy this file using C# File.Copy (unauthorizedaccessexception, access denied), here is my code:
SqlConnection myConn = new SqlConnection("Server=" + sqlname + ";Integrated security=SSPI;database=master");
string dbname = "tmpDB" + DateTime.Now.Ticks.ToString();
str = "CREATE DATABASE " + dbname + " ON PRIMARY " +
"(NAME = MyDatabase_Data, " +
"FILENAME = '" + System.IO.Path.GetDirectoryName(openDialogConvert.FileName) + "\\" + dbname + ".mdf') " +
"LOG ON (NAME = MyDatabase_Log, " +
"FILENAME = '" + System.IO.Path.GetDirectoryName(openDialogConvert.FileName) + "\\" + dbname + ".ldf') ";
SqlCommand myCommand = new SqlCommand(str, myConn);
try
{
myConn.Open();
myCommand.ExecuteNonQuery();
}
catch (System.Exception ex)
{
MessageBox.Show(ex.ToString(), "MyProgram", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
myCommand.Dispose();
str = #"RESTORE DATABASE [" + dbname + "] FROM DISK = N'" + openDialogConvert.FileName + #"' WITH FILE = 1, MOVE N'IODB_Data'
TO N'" + System.IO.Path.GetDirectoryName(openDialogConvert.FileName) + "\\" + dbname + #".mdf', MOVE N'IODB_Log'
TO N'" + System.IO.Path.GetDirectoryName(openDialogConvert.FileName) + "\\" + dbname + #".ldf', REPLACE ";
myCommand = new SqlCommand(str, myConn);
myCommand.ExecuteNonQuery();
myCommand.Dispose();
myConn.Close();
//here I'm going to connect to my newly created & restored database, but I get access denied error
SqlConnection sql = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=" + System.IO.Path.GetDirectoryName(openDialogConvert.FileName) + #"\" + dbname + ".mdf ;Integrated Security=True");
sql.Open();
What is going wrong here? I want to connect to my newly restored database as soon as I restore my database.
I get following error when I try to connect to my newly created & restored .mdf:
Unable to open the physical file "D:\9 mordad fara\Ofogh-Dsk\Ofogh-Dsk\bin\Debug\tmpDB635110451805001328.mdf". Operating system error 5: "5(Access is denied.)".
An attempt to attach an auto-named database for file D:\9 mordad fara\Ofogh-Dsk\Ofogh-Dsk\bin\Debug\tmpDB635110451805001328.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.
I suspect it may be already attached.
Can you connect using:
new SqlConnection("Server=" + sqlname +
";Integrated security=SSPI;" +
"database=" + dbname);
I have an c# winforms application (.net 2 framework).
I need to backup data bases from my application.
I am trying to do this by executing an SqlCommand asynchronously.
The code is executed with no exceptions but I dont get the .bak file in my destination...
this is the code :
#region backup DB using T-SQL command
string connString = "Data Source=" + ConfigurationManager.AppSettings.Get("localhost_SQLEXPRESS") + ";Initial Catalog=" + db + ";UserID=" + ConfigurationManager.AppSettings.Get("user") + ";Password=" + ConfigurationManager.AppSettings.Get("password");
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(connString);
builder.AsynchronousProcessing = true;
using (SqlConnection sqlConnection1 = new SqlConnection(builder.ConnectionString))
{
using (SqlCommand cmd = new SqlCommand("BACKUP DATABASE " + db + " TO DISK=" + location + "\\" + ConfigurationManager.AppSettings.Get("DataBaseBackupsFolderName") + "\\" + db + ".bak'", sqlConnection1))
{
sqlConnection1.Open();
IAsyncResult result = cmd.BeginExecuteNonQuery();
while (!result.IsCompleted)
{
Thread.Sleep(100);
}
}
}
#endregion
In your SQL backup line you seem to be missing a single quote at the beginning of the path to the backup file.
using (SqlCommand cmd = new SqlCommand("BACKUP DATABASE " + db + " TO DISK='" + location + "\\" + ConfigurationManager.AppSettings.Get("DataBaseBackupsFolderName") + "\\" +db + ".bak'", sqlConnection1))
Two advices to try to isolate the problem:
1) Get the resulting string (the one you are executing on the SqlCommand and run it manually on SQL Server to make sure the backup commnad is correct.
2) Try a synchronous command with a regular ExecuteNonQuery to see if you are getting a SQL Server exception
You should call EndExecuteNonQuery() on your SqlCommand instance in order to throw any eventual exception and thus understand what is wrong with your SQL statements:
IAsyncResult result = cmd.BeginExecuteNonQuery();
// Wait for the command to complete
result.AsyncWaitHandle.WaitOne();
// End the execution and throw any eventual exception
cmd.EndExecuteNonQuery(result);
As you can see, I have also replaced your original Thread.Sleep() cycle block with a more effective wait on the wait handle of the command.
Quoting MSDN:
For each call to BeginOperationName, the application should also call
EndOperationName to get the results of the operation.
I Have written 2 methods in C# . one for getting records from excel sheet and one for inserting into excel sheet. both methods works fine when im running in my local system. but when i hosted it to appHarbor.com, getting records succeded but inserting failed.
here is the insert method
private bool AddBlessingToExcel(Blessing blessing)
{
try
{
string path = System.Web.HttpContext.Current.Server.MapPath("Data") + "/WeddingSheets.xls";
OleDbConnection myConnection = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties=Excel 8.0");
// always read from the sheet1.
OleDbCommand myCommand = new OleDbCommand("Insert into [Blessings$] (GuestName, GuestLocation, GuestMessage)" + " values ('" + blessing.GuestName + "', '" + blessing.GuestLocation + "', '" + blessing.GuestMessage + "')");
myConnection.Open();
myCommand.Connection = myConnection;
int val = myCommand.ExecuteNonQuery();
//Close the connection.
myConnection.Close();
return true;
}
catch(Exception ex)
{
//throw ex;
return false;
}
}
i dont know what the problem is exactly but my guess is its because of file permissions..can anyone please provide me a solution as soon as possible.
Inside the "Settings" page of the application, at the top of the page you should see an option named "Enable file system write access", with a checkbox next to it.
That should give your app write access. However, I believe this gets reset every time you build, so you might have to enable it again after a new deployment.