Click here to Skip to main content
15,891,943 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I want to restore the data using c#, but it is showing an error.

Error:

Incorrect syntax near 'DISK'.

Incorrect syntax near the keyword 'with'. If this statement is a common table expression, an xmlnamespaces clause or a change tracking context clause, the previous statement must be terminated with a semicolon.


Please help me.

What I have tried:

private void button2_Click(object sender, EventArgs e)
        {

            string servername = textBox1.Text;
            string databasename = textBox3.Text;

            SqlConnection con = new SqlConnection(@"Data Source =" + servername + " ; Initial Catalog=" + databasename + "; Integrated Security =True");

            con.Open();

            string str = "USE master;";
            string str1 = "ALTER DATABASE " + databasename + " SET SINGLE_USER WITH ROLLBACK IMMEDIATE";
            string str3 = "RESTORE DATABASE " + databasename + "FROM DISK = '" + textBox2.Text + "' WITH REPLACE ";

            SqlCommand cmd = new SqlCommand(str, con);
            SqlCommand cmd1 = new SqlCommand(str1, con);
            SqlCommand cmd3 = new SqlCommand(str3, con);

            cmd.ExecuteNonQuery();
            cmd1.ExecuteNonQuery();
            cmd3.ExecuteNonQuery();
            MessageBox.Show("DATABASE RECOVERED Successful. if you want to get the recovered data you must close the software and rerun again.");
            con.Close();
            Application.Exit();
            this.Hide();            
        }
Posted
Updated 19-Mar-20 7:27am

Have a look at this: Backing up an SQL Database in C#[^] - there are classes specifically for backup and restore.
 
Share this answer
 
You are missing a whitespace between the database name and the FROM clause in str3:
C#
string str3 = $"RESTORE DATABASE {databasename} FROM DISK = '{textBox2.Text}' WITH REPLACE ";

Note that building a SQL query by concatenating strings, especialy when one of them is obtained from user input, leaves your code wide open to SQL injection attacks.
If someone were to enter '; DELETE DATABASE (databasename);-- in textBox2, for example, corresponding database would be deleted and the only option which would remain would be to restore it from a backup. (You can search for frequents answers by OriginalGriff about it, who explains that much better than I). It is also advised to enclose resource-intensive, disposable resources, like a SQL command for example, in an using block. This would also be true for your connection object.

Edit: unfortunately, you cannot use a parameterized query with a RESTORE command. I modified the following block to avoid the confusion. Keep in mind the using-block trick, though; this is a habit worth catching.
C#
using (SqlConnection con = new SqlConnection($"Data Source={servername}; Initial Catalog={databasename}; Integrated Security=True"))
{
   con.Open();
   // ...
   string str3 = $"RESTORE DATABASE {databasename} FROM DISK = '{textBox2.Text}' WITH REPLACE ";
   using (SqlCommand cmd3 = new SqlCommand(str3, con))
   {
      cmd3.ExecuteNonQuery();
      // ...
   }
}

But note that solution 1 points to a much cleaner way to backup your database, anyway.
 
Share this answer
 
v4
Comments
ishuishika 20-Mar-20 2:41am    
Thank you so much... it resolved my issues.

For sure I'll follow what you said.. :)
phil.o 20-Mar-20 4:56am    
You're welcome :)
I fear you missed a space in the query:
C#
string str3 = "RESTORE DATABASE " + databasename + " FROM DISK = '" + textBox2.Text + "' WITH REPLACE ";
//                                                  ^ a space was missing here

Building a sql query by string concatenation is a bad idea because it is vulnerable to 'SQL Injection' as already spotted in other solutions.

Not a solution to your question, but another problem you have.
Never build an SQL query by concatenating strings. Sooner or later, you will do it with user inputs, and this opens door to a vulnerability named "SQL injection", it is dangerous for your database and error prone.
A single quote in a name and your program crash. If a user input a name like "Brian O'Conner" can crash your app, it is an SQL injection vulnerability, and the crash is the least of the problems, a malicious user input and it is promoted to SQL commands with all credentials.
SQL injection - Wikipedia[^]
SQL Injection[^]
SQL Injection Attacks by Example[^]
PHP: SQL Injection - Manual[^]
SQL Injection Prevention Cheat Sheet - OWASP[^]
How can I explain SQL injection without technical jargon? - Information Security Stack Exchange[^]
 
Share this answer
 
v2
Comments
Richard Deeming 19-Mar-20 14:00pm    
Unfortunately, there isn't a way to use parameters with a RESTORE DATABASE command.

But if you don't trust the user who's running this code, then SQL Injection is the least of your concerns! :)
ishuishika 20-Mar-20 2:14am    
@ Patrice T ..thank you so much... After giving space it's working fine now..

Really i wasn't knowing that that the simple space between " FROM was the resolution for my problem.
once again thank you so much..
Patrice T 20-Mar-20 2:17am    
You're welcome
I told you yesterday that you need to examine the actual SQL commands that you are generating. The final text produced by your c ode is obviously incorrect, and the only way to find out why is to use the debugger and examine it in detail. No one here can do that for you.
 
Share this answer
 
v2
Comments
ishuishika 19-Mar-20 4:15am    
I'm sorry..

I'm trying my level best to resolve the problem from my end itself. But when I'm not able to resolve it I don't have any guider except updating in this website.
For the time being I have to complete my mini project by this month. That is the reason I was updating in this web for the quicker resolution.

Once again apologize me. I'll debug and examine from my end itself.

Thank you.
Richard MacCutchan 19-Mar-20 6:01am    
People here are happy to help with technical issues, but you are expected at least to gather all the information first. Remember we cannot see your screen or run your code, we rely on you to do the testing.

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