Click here to Skip to main content
15,917,875 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am Trying to take backup of my database in c#. I wrote some code for that. While I am trying to execute it is telling syntax error. Help me with this.

Here My code
C#
string database = con.Database.ToString();
try
{
    if (textBox1.Text == string.Empty)
    {
        MessageBox.Show("Please Enter Path");
    }
    else
    {
        string cmd = ("BACKUP DATABASE [" + database + "] TO DISK '" + textBox1.Text + "\\" + "Database" +"-"+ DateTime.Now.ToString("yyyy-MM-dd--HHmmss")+".bak'");
        using (SqlCommand command = new SqlCommand(cmd, con))
        {
            if (con.State != ConnectionState.Open)
            {
                con.Open();
            }
            command.ExecuteNonQuery();
            con.Close();
            MessageBox.Show("Backup Completed Successfully");
        }
    }
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message);
}


What I have tried:

I am unable to trace that error.
Posted
Updated 10-May-17 22:42pm
v4

Try this: Backing up an SQL Database in C#[^]

And never use SQL like that! Never concatenate strings to build a SQL command. It leaves you wide open to accidental or deliberate SQL Injection attack which can destroy your entire database. Use Parametrized queries instead. SQL Injection vulnerable code when you try to backup? That's just plain stupid as well as dangerous...
 
Share this answer
 
Comments
vijay_bale 11-May-17 4:32am    
That one ok. I am trying that. But here where is syntax error. I want to know even my writing method is wrong. Can you tell me that. I wont repeat that in future.
OriginalGriff 11-May-17 4:44am    
Look like you spotted it - but do check the rest of your code: if you leave one instance in where the user gets to type directly into your DB, someone will delete your DB for you...
vijay_bale 11-May-17 6:27am    
I removed that code. I am doing like that link what you gave.
Finally I traced. I missed to enter "=" sign after disk.
string cmd = ("BACKUP DATABASE [" + database + "] TO DISK=
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900