How to restore back up programmatically - c#

I created a backup on button click
My code for this is
con.Open();
string str = "USE [C:\\Users\\asus\\Documents\\Visual Studio 2012\\Projects\\bbcon_accout_software\\bb_con_accnt_soft_lib\\BbCon.mdf]";
string str1 = "BACKUP DATABASE [C:\\Users\\asus\\Documents\\Visual Studio 2012\\Projects\\bbcon_accout_software\\bb_con_accnt_soft_lib\\BbCon.mdf] TO DISK = 'C:\\Users\\Public\\aa.Bak' WITH FORMAT,MEDIANAME = 'Z_SQLServerBackups',NAME = 'Full Backup of Testdb';";
SqlCommand cmd1 = new SqlCommand(str, con);
SqlCommand cmd2 = new SqlCommand(str1, con);
cmd1.ExecuteNonQuery();
cmd2.ExecuteNonQuery();
MessageBox.Show("success");
con.Close();
Now I would like to restore the backed up database, please help I searched lots of questions, but I didn't get the answer I need - please help me to perform this task.
I tried to restore using this code:
string query = "RESTORE DATABASE BbCon FROM DISK='C:\\Users\\Public\\aa.Bak' WITH REPLACE";
con.Open();
using (SqlCommand cmd = new SqlCommand(query, con))
{
cmd.ExecuteNonQuery();
}
con.Close();
but I am getting an error
Please help me with this

Each of the physical files needs to reside somewhere on the system that you're attempting to restore the backed up database to. The error message is telling you that the files are in use by another database. You can query sys.master_files to find out which database they belong to.
To resolve this, you need to either delete the database that is using those physical files or add a MOVE clause into your RESTORE statement. For the latter, it would look something like this:
RESTORE DATABASE BbCon FROM DISK='C:\\Users\\Public\\aa.Bak' WITH REPLACE,
move 'BBCon' to 'c:\temp\BBCon.mdf',
move 'BBCon_log' to 'c:\temp\BBCon_log.ldf';

Related

Getting a database error when trying to view data

Alright,
I have a page that interacts with my SQL data connection. it tries to run a stored procedure, but every time I run it, it locks out of the database showing this error:
Here's the code the fires of the connection and stored procedure `
FileUpload1.SaveAs(Server.MapPath("images//" + FileUpload1.FileName));
string Image = MapPath("images//" + FileUpload1.FileName);
SqlConnection con = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\BOOKS.mdf;Integrated Security=True;User Instance=True");
SqlCommand cmd = new SqlCommand("AddaBook", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Title", SqlDbType.NVarChar).Value = txtTitle.Text;
cmd.Parameters.AddWithValue("#Image", SqlDbType.NVarChar).Value = Image;
cmd.Parameters.AddWithValue("#Author", SqlDbType.NVarChar).Value = txtAuthor.Text;
cmd.Parameters.AddWithValue("#PublishDate", SqlDbType.DateTime).Value = txtPublishDate.Text;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
cmd.Connection.Close();
lblUploadResult.Text = "File uploaded successfully.";
lblUploadResult.ForeColor = System.Drawing.Color.ForestGreen;
}`
Any help is appreciated and always thank you!
Try moving your mdf file out of OneDrive. Sometime when OneDrive is doing an upload, or one of the many other processes it does, it will lock the files - especially from system user.
It is saying that your database is under usage so you can not access it.
Be sure that no other code is accessed in the database without closing the connection.
You may also update the code with the following as some not needed lines are removed.
SqlConnection con = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\BOOKS.mdf;Integrated Security=True;User Instance=True");
SqlCommand cmd = new SqlCommand("AddaBook", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Title", SqlDbType.NVarChar).Value = txtTitle.Text;
cmd.Parameters.AddWithValue("#Image", SqlDbType.NVarChar).Value = Image;
cmd.Parameters.AddWithValue("#Author", SqlDbType.NVarChar).Value = txtAuthor.Text;
cmd.Parameters.AddWithValue("#PublishDate", SqlDbType.DateTime).Value = txtPublishDate.Text;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
lblUploadResult.Text = "File uploaded successfully.";
lblUploadResult.ForeColor = System.Drawing.Color.ForestGreen;
You already have the file open but just don't know it. For example, if you are trying to open a text file called Test.txt (or conversely a .mdf database file which has already been opened), then you will get this error, which is also why you are likely getting the other errors down the line but all related to this first error.
With databases, things can get a bit tricky, because you can connect to a database and at times get an error and be kicked out of the system without closing the connection or process... at which point a currently running but unknown process may be keeping the connection alive. You can look at all open processes on your system or see if you mistakenly have the connection open and then close it before trying to open it through the application.

c# update database isn't working

So I've searched the net to find a solution and what I found is that when we execute F5 in visual studio, it actually copies the original database into a new one and it uses the copy in the code so the changes you'd have made wouldn't be there and they told me to set the database properties to "Copy if newer" and it isn't working, I don't get any error messages but the original is not being updated.
I made a test to see if this code was updating at least the copy and it is...
After running my application when I see the database the changes aren't there
So I want to update the original database how do I do that?
private void button3_Click(object sender, EventArgs e)
{
string connectionString = ConfigurationManager.ConnectionStrings["NembManagement.Properties.Settings.NembDatabaseConnectionString"].ConnectionString;
using (connection = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand("UPDATE Alunos SET Nome = #a WHERE Id=1", connection))
{
DataTable AlunosInfo = new DataTable();
connection.Open();
command.Prepare();
command.Parameters.Clear();
command.Parameters.AddWithValue("#a","aff");
command.ExecuteNonQuery();
//test to see if it was updating the copy and it is
SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM Alunos WHERE Alunos.Id=1 ", connection);
adapter.Fill(AlunosInfo);
}
}
I found the solution somehow, i changed my database property Copy to nevercopy and i got another error saying that connection could not be opened so i solved this one by correcting the connection string in the app config

How to add items to existing database thru application form

I currently have a dataset and would like to continually add new items to that dataset (like type a new entry in a textbox and add it with a button) and edit current items via the applications form I created.
How would I go about tackling this issue?
edit:
This was the best base start I could come up with watching videos and going through google. Dictionary.mdf is my dataset
SqlCommand cmd = new SqlCommand("insert into dictionary(word, definition) values(#word, #definition)");
cmd.Parameters.AddWithValue("#word", textBoxWordtoAdd.Text);
cmd.Parameters.AddWithValue("#definition", textBoxDefinition.Text);
this.Close();
I think you are missing the cmd.ExecuteNonQuery();
If you were using Ms Sql Server. Then your code should look something like this:
using(SqlConnection connection = new SqlConnection(ConnectionString))
{
connection.Open();
string sql = "insert into dictionary(word, definition) values(#word, #definition)";
SqlCommand cmd = new SqlCommand(sql,connection);
cmd.Parameters.Add("#word", SqlDbType.Varchar, 50).value = textBoxWordtoAdd.Text;
cmd.Parameters.Add("#definition", SqlDbType.Varchar, 50).value = textBoxDefinition.Text;
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
You also need to open a conneciton which I don't see in your code, but I assume you do it somewhere. Just replace the ConnectionString in the code with your own connection string.

How to refresh database through c sharp coding in dot net

I am developing a windows project in dot net using c sharp language and the back-end is sql server database.
What I am doing is that there is a SQL query to insert data in the table as
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source = ...........";
con.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO TableName(column1, column2) VALUES(txtBox1, txtBox2)", con);
SqlDataAdapter adp = new SqlDataAdapter(cmd);
Dataset ds = new Dataset();
Now, what problem I am facing here is that when I try to access this table in another windows form using Microsoft Report Viewer. Then, there the data newly inserted is not accessible since it needs the database to be refreshed.
Please tell me how can I resolve this problem.
Thanks in advance
Deepak
i don't think that you need to refresh it, just request it from db and commit transaction if you are using it. But if you want to share data between your forms use Registry pattern to achieve this.
Registry is class which will hold data for you, and you can access it from anywhere but use static variables and methods.
public class Registry
{
public static DataTable Users;
}
And if you change data from one form all forms will have updated data.
It seems there are many error,change this line
SqlCommand cmd = new SqlCommand("INSERT INTO TableName(column1, column2) VALUES(txtBox1, txtBox2)", con);
to
SqlCommand cmd = new SqlCommand(String.format("INSERT INTO TableName(column1, column2) VALUES('{0}', '{1}')",txtBox1.Text,txtBox2.Text), con);
and your command never executed on database

Looking for code which will let me backup SQL Server 2005/2008/2008R2 database inside C# tests (MSTest)

I have found a starting point below, but I worry that I can miss calls to CreateDbBackup() and RestoreDbBackup(). I was hoping that I could write and use an attribute on my tests. Is this possible? How? I am using MSTest library and C# 4.0.
http://www.linglom.com/2008/01/12/how-to-backup-and-restore-database-on-microsoft-sql-server-2005/
internal void CreateDbBackup()
{
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["myConStr"].ConnectionString))
{
SqlCommand cmd = con.CreateCommand();
cmd.CommandText = string.Format(#"BACKUP DATABASE [MyDatabase] TO DISK = N'{0}' WITH INIT , NOUNLOAD , NOSKIP , STATS = 10, NOFORMAT", UtilityClassGeneral.DbBackupPath);
con.Open();
cmd.ExecuteNonQuery();
}
}
internal void RestoreDbFromBackup()
{
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["myConStr"].ConnectionString))
{
SqlCommand cmd = con.CreateCommand();
con.Open();
// Make sure to get exclusive access to DB to avoid any errors
cmd.CommandText = "USE MASTER ALTER DATABASE [MyDatabase] SET SINGLE_USER With ROLLBACK IMMEDIATE";
cmd.ExecuteNonQuery();
cmd.CommandText = string.Format(#"RESTORE DATABASE [MyDatabase] FROM DISK = N'{0}' WITH FILE = 1, NOUNLOAD , STATS = 10, RECOVERY , REPLACE", UtilityClassGeneral.DbBackupPath);
cmd.ExecuteNonQuery();
}
}
Have a look at SQL Server Management Objects (SMO). You should be able to use this to backup and restore SQL Server databases.

Categories

Resources