How to backup database (SQL Server 2008) in C# without using SMO?
15,314
Solution 1
You need to assign that SqlConnection object to the SqlCommand - try this code:
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
string connStr = "Data Source=M1-PC;Initial Catalog=master;Integrated Security=True;Pooling=False";
using(SqlConnection conn = new SqlConnection(connStr))
{
string sqlStmt = String.Format("BACKUP DATABASE LA TO DISK='{0}'", saveFileDialog1.FileName);
using(SqlCommand bu2 = new SqlCommand(sqlStmt, conn))
{
conn.Open();
bu2.ExecuteNonQuery();
conn.Close();
MessageBox.Show("ok");
}
}
}
Solution 2
You never tell your SqlCommand which connection to use (this is what the error message says by the way, did you read it?). Either set the Connection
property or use SqlConnection.CreateCommand to create the command in the first place.
Author by
Saleh
Updated on June 04, 2022Comments
-
Saleh almost 2 years
I have this code and it is not working but I don't why?
try { saveFileDialog1.Filter = "SQL Server database backup files|*.bak"; saveFileDialog1.Title = "Database Backup"; if (saveFileDialog1.ShowDialog() == DialogResult.OK) { SqlCommand bu2 = new SqlCommand(); SqlConnection s = new SqlConnection("Data Source=M1-PC;Initial Catalog=master;Integrated Security=True;Pooling=False"); bu2.CommandText = String.Format("BACKUP DATABASE LA TO DISK='{0}'", saveFileDialog1.FileName); s.Open(); bu2.ExecuteNonQuery(); s.Close(); MessageBox.Show("ok"); } } catch (Exception ex) { MessageBox.Show(ex.ToString()); }
and I get this error :
What is the problem?
-
Saleh about 14 yearsWhen I use your code I get this error messege, i44.tinypic.com/5mbhxx.png - What is the proplem?
-
marc_s about 14 yearsWell, does your SQL Server really have a directory
C:\Users\Saleh\Documents
??? Remember: the backup will be done on the SQL Server machine - it will NOT be to your own local PC! -
JamesT about 9 yearsThis already has an accepted answer and yours doesn't appear to add anything to it.
-
tugberk over 8 yearsnever say that a piece of code is 100% correct! It's either wrong or you will jinx it...