You are missing a whitespace between the database name and the
FROM
clause in
str3
:
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.
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.