0

I'm stuck on a issue where I need to backup my database via Winforms. I managed to find a sample SQL code in order to achieve this task.

My query here :

SqlConnection CON = new SqlConnection("Data Source=DBS\\DB;Initial Catalog=" + metroTextBox1.Text + ";Integrated Security=True");

Sql = "BACKUP DATABASE " + metroComboBox1.Text + " TO DISK = '" + metroTextBox4.Text + "\\" + metroComboBox1.Text + "-" + DateTime.Now.Ticks.ToString() + ".bak'";

I have no idea how to proceed next. What should I use in this scenario? (ExecuteScalar, ExecuteNonQuery..etc)

Any help would be appreciated.

Note that Date time is also there in back up file name.

2 Answers 2

1

You define the SQL command to execute, and then instantiate a SqlCommand. Since the SQL statement isn't expected to return any data (a result set etc.), use ExecuteNonQuery:

string Sql = "BACKUP DATABASE " + metroComboBox1.Text + " TO DISK = '" + metroTextBox4.Text + "\\" + metroComboBox1.Text + "-" + DateTime.Now.Ticks.ToString() + ".bak'";

using(SqlConnection CON = new SqlConnection("Data Source=DBS\\DB;Initial Catalog=" + metroTextBox1.Text + ";Integrated Security=True"))
using(SqlCommand cmdBackup = new SqlCommand(Sql, CON))
{   
    // open connection, execute command, close connection
    CON.Open();
    cmdBackup.ExecuteNonQuery();
    CON.Close();
}
Sign up to request clarification or add additional context in comments.

Comments

0

The general code:

using (var conn = new SqlConnection(connString))
{
    conn.Open();
    using (var comm = conn.CreateCommand())
    {
        comm.CommandType = CommandType.Text;
        comm.CommandText = "BACKUP DATABASE...";
        comm.ExecuteNonQuery();
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.