How to restore SQL Server backups using asp.net and C#? - c#

How to restore SQL Server backup using C#?
try
{
string test = "D:\\backupdb\\05012017_130700.Bak";
sqlcmd = new SqlCommand("Restore database EmpolyeeTable from disk='D:\\backupdb\\05012017_130700.Bak'", con);
sqlcmd.ExecuteNonQuery();
Response.Write("restore database successfully");
}
catch (Exception ex)
{
Response.Write("Error During backup database!");
}

Quite weird requerement you have right there. I´ve never heard of someone restoring a database backup from a webpage, and as #Alex K. told, it would be quite rare that the user that uses your web application have the required previleges.
Anyway, supposing that everything told above is OK, the code to restore a backup would be this:
Use this:
using System.Data;
using System.Data.SqlClient;
Code:
private void TakeBackup()
{
var conn = new SqlConnection("Data Source=" + Server + ";Initial Catalog=" + Database + ";User Id=" + Username + ";Password=" + Password + ";");
try
{
conn.Open();
SqlCommand command = conn.CreateCommand();
command.CommandText = "RESTORE DATABASE AdventureWorks FROM DISK = 'C:\AdventureWorks.BAK' WITH REPLACE GO";
command.ExecuteNonQuery();
}
catch (Exception)
{
throw;
}
finally
{
conn.Dispose();
conn.Close();
}
}
This is going to work specifically for the problem you posted. Be sure to set all the parameters of your database server on the connection string, it seems from the comments on your question that you are having communication issues. You have to solve that problems before you do anything. Some tips for that:
Be sure you set all the parameters on connection string the right way
Try to connect using another tool like ODBC so you can test all parameters
Check out SQL Network settings to see if TCP/IP is enabled

Related

I'm trying to backup and restore database from SQL Server 2008

I'm trying to backup and restore a SQL Server 2008 database, but I'm getting an error saying
Incorrect Syntax near database name
Here is the code for back up and restore which is written c# asp.net.
Can I get a help regarding this?
private void btnbackup_Click(object sender, EventArgs e)
{
try
{
if (combodatabase.Text.CompareTo("") == 0)
{
MessageBox.Show("Please select a Database");
return;
}
con = new SqlConnection(connectionstring);
con.Open();
sql = "BACKUP DATABASE" + combodatabase.Text + " TO DISK='" + txtbackupfileloc.Text + "\\" + combodatabase.Text + "-" + DateTime.Now.Ticks.ToString() + ".bak'";
cmd = new SqlCommand(sql, con);
cmd.ExecuteNonQuery();
con.Close();
con.Dispose();
MessageBox.Show("Database Backup Successfully Completed.");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Restore code:
private void btnrestore_Click(object sender, EventArgs e)
{
try
{
if (combodatabase.Text.CompareTo("") == 0)
{
MessageBox.Show("Please Select a Database");
return;
}
con = new SqlConnection(connectionstring);
con.Open();
sql = "ALTER DATABASE" + combodatabase.Text + "SET SINGLE_USR WITH ROLLBACK IMMEDIATELY ";
sql += "RESTORE DATABASE" + combodatabase.Text + "From DISK='" + txtrestorefileloc.Text + "'With REPLACE;";
cmd = new SqlCommand(sql, con);
cmd.ExecuteNonQuery();
con.Close();
con.Dispose();
MessageBox.Show("Database Successfully Restored");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
You don't have any whitespace between BACKUP DATABASE and the database name, that will be the first problem, the same goes for the second (restore) code.
You could attach yourself in debug mode to see what is the SQL command after you have built all your sql query string. It seems a lot of whitespaces are missing there. Once you have it, you could post it in SQL Server Management Studio and see tips for errors there, would be easier probably.
Last, but not least, if you can't debug your application easily or pop up the SQL query (which apparently isn't the case since you display the ex.Message), you could maybe run a SQL Server Profiler session to check the queries executed against SQL Server.
You're missing a few spaces in your SQL statements!
Check this out:
sql = "BACKUP DATABASE" + combodatabase.Text + " TO DISK='" + ....
If you select a database called TEST, this becomes:
BACKUP DATABASETEST TO DISK=.....
Or this:
sql = "ALTER DATABASE" + combodatabase.Text + "SET SINGLE_USR WITH ROLLBACK IMMEDIATELY ";
sql += "RESTORE DATABASE" + combodatabase.Text + "From DISK='" + txtrestorefileloc.Text + "'With REPLACE;";
becomes
ALTER DATABASETESTSET SINGLE_USR WITH ROLLBACK IMMEDIATELY
RESTORE DATABASETESTFrom DISK=......
There needs to be at least one space between the BACKUP DATABASE and the name of the database! Some throughout your code - you need to be more careful when stringing together keywords and placeholder - you need spaces between them at times!
Also, if your database name is "special" in any way (e.g. it contains a space itself, starts with a number etc.), you might need to put the database name into square brackets:
BACKUP DATABASE [Test DB] .....
BACKUP DATABASE [7dwarfs] .....

Unable to connect to any of the specified MySQL hosts

I know that it is an easy problem but I can't find the error. I want to save data in my database. I create a database named "Examen" with Microsoft SQL Server 2008 then in my app in visual studio I make the connection string like this :
string connectionstring = #"Data Source=.\sqlexpress;Initial Catalog=Examen;Integrated Security=True";
Then I use this code to insert data into a "Test" table:
MySqlConnection connection = new MySqlConnection(connectionstring);
MySqlCommand cmd;
connection.Open();
try
{
cmd = connection.CreateCommand();
cmd.CommandText = "Insert into Examen.Test (nom,prenom) values (" + txbnom.Text + "," + txbprenom.Text + ") ";
cmd.ExecuteNonQuery();
MessageBox.Show("ok");
}
catch (Exception)
{
throw;
}
finally
{
if(connection.State == ConnectionState.Open)
{
connection.Close();
}
}
When running this code i had an error when openning the connection
Unable to connect to any of the specified MySQL hosts.
You are mixing MySQL and MSSQL.
Are you sure you want to connect to a MySQL server? Use http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection(v=vs.110).aspx if you would like to connect to MSSQL.
Also you should make yourself familiar with SQL injection

Connect to a database not created yet?

How do I create a SQL Compact Edition database? I have tried to figure it out, searched the internet and I cant find it (but then again, how do you search for this?!). Here is my code so far:
checkPasswordsMatch();
SqlCEConnection myconn = new SqlCEConnection();
SqlCeCommand myCommand = new SqlCeCommand(
#"CREATE DATABASE ""pwdb.sdf"" DATABASEPASSWORD '" + textBox1.Text + "'");
myCommand.ExecuteNonQuery();
What do I put on the connection part? I dont understand.
UPDATE: I decided to create a database to incorporate with the application, and simply check if there was a value (admin Password) dedicated to the record Master.
Here is my new code:
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
SqlCeConnection myconn = new SqlCeConnection("Data Source = pwdb.sdf;");
SqlCeCommand checkpass = new SqlCeCommand("SELECT * from PW WHERE Name = Master;",myconn);
try
{
myconn.Open();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
if (checkpass.ExecuteNonQuery() != null)
{
Application.Run(new enterMasterPassword());
}
else
Application.Run(new mainPassSet());
The problem is, when i execute this now, i get:
An unhandled exception of type 'System.Data.SqlServerCe.SqlCeException' occurred in System.Data.SqlServerCe.dll
Any ideas anyone??
Try using the SqlCeEngine class. With that class you can create a new database:
using (SqlCeEngine engine = new SqlCeEngine())
{
engine.LocalConnectionString = yourConnectionString;
engine.CreateDatabase();
}
Since you likely only want to create the database once you may not want to do it in your code.
A couple suggestions:
1) if you're using Visual Studio you can open the Server Explorer (Under menu View->Server Explorer) and create it there.
2) Use one of the free SQL managers like linkpad or powershell + sqlcmd (there are others)
3) or... Don't know what data model you are using but EntityFramework with "code first" will create the database for you automatically based on your connection string and how you name your data context. Since you are using the sdf tag, maybe you are using EF...

Connecting to a database in C#

I feel like an absolute idiot. I've been trying to connect to a database I created for a few hours now and I can't seem to get it to connect. Here is my code.
string chooseMoodCmbBx = moodCmbBx.SelectedIndex.ToString();
string source = "Data Source='E:\\Documents\\Database\\MyDatabase.sdf';" +
"Password='password';" +
"Persist Security Info=False;";
SqlConnection conn = new SqlConnection(source);
try
{
conn.Open();
MessageBox.Show("Succesfully Connected");
}
catch (SqlException ex)
{
MessageBox.Show(ex.ToString());
}
You have an SDF file, meaning that you connect to a Sql Compact not to Sql Server. You need to use the classes in the namespace System.Data.SqlServerCe
SqlCeConnection conn = new SqlCeConnection(source);
Also, I am not sure of this, but I think you don't need to have single quotes around values in the connection string
string source = "Data Source=E:\\Documents\\Database\\MyDatabase.sdf;" +
"Password=password;" +
"Persist Security Info=False;";

Dropping SQL Server database through C#

I am using this code to delete a database through C#
Int32 result = 0;
try
{
String Connectionstring = CCMMUtility.CreateConnectionString(false, txt_DbDataSource.Text, "master", "sa", "happytimes", 1000);
SqlConnection con = new SqlConnection();
con.ConnectionString = Connectionstring;
String sqlCommandText = "DROP DATABASE [" + DbName + "]";
if (con.State == ConnectionState.Closed)
{
con.Open();
SqlConnection.ClearPool(con);
con.ChangeDatabase("master");
SqlCommand sqlCommand = new SqlCommand(sqlCommandText, con);
sqlCommand.ExecuteNonQuery();
}
else
{
con.ChangeDatabase("master");
SqlCommand sqlCommand = new SqlCommand(sqlCommandText, con);
sqlCommand.ExecuteNonQuery();
}
con.Close();
con.Dispose();
result = 1;
}
catch (Exception ex)
{
result = 0;
}
return result;
But I get an error
Database currently in use
Can anyone help?
Try this:
String sqlCommandText = #"
ALTER DATABASE " + DbName + #" SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
DROP DATABASE [" + DbName + "]";
Also make sure that your connection string defaults you to the master database, or any other database other than the one you're dropping!
As an aside, you really don't need all of that stuff around your queries. The ConnectionState will always start off Closed, so you don't need to check for that. Likewise, wrapping your connection in a using block eliminates the need to explicitly close or dispose the connection. All you really need to do is:
String Connectionstring = CCMMUtility.CreateConnectionString(false, txt_DbDataSource.Text, "master", "sa", "happytimes", 1000);
using(SqlConnection con = new SqlConnection(Connectionstring)) {
con.Open();
String sqlCommandText = #"
ALTER DATABASE " + DbName + #" SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
DROP DATABASE [" + DbName + "]";
SqlCommand sqlCommand = new SqlCommand(sqlCommandText, con);
sqlCommand.ExecuteNonQuery();
}
result = 1;
Here is how you do it using Entity Framework version 6
System.Data.Entity.Database.Delete(connectionString);
You should take a look at SMO.
These allow you to manage all aspects of SQL Server from code, including deleting of databases.
The database object has a Drop method to delete database.
Create sqlconnection object for different database other than you want to delete.
sqlCommandText = "DROP DATABASE [DBNAME]";
sqlCommand = new SqlCommand(sqlCommandText , sqlconnection);
sqlCommand.ExecuteNonQuery();
In this case i would recommend that you take the database offline first... that will close all connections and etc... heres an article on how to do it: http://blog.sqlauthority.com/2010/04/24/sql-server-t-sql-script-to-take-database-offline-take-database-online/
Microsoft clearly states that A database can be dropped regardless of its state: offline, read-only, suspect, and so on. on this MSDN article (DROP DATABASE (Transact-SQL))
Connection pooling at a guess, use sql server's activity monitor to make sure though.
Pooling keeps connections to the database alive in a cache, then when you create a new one, if there's one in the cache it hands it back instead of instantiating a new one. They hang around for a default time, (2 minutes I think) if they don't get re-used in that time, then they killed off.
So as a first go connect straight to master, instead of using change database, as I suspect change database will simply swap connections in the pool.
Add a check routine for database in use (use a connection to master to do it!). You can force the database to be dropped anyway by first executing
ALTER DATABASE [MyDatabase] SET SINGLE_USER WITH ROLLBACK IMMEDIATE
again from the connection to master!
However everybody else using the db, will no longer like you at all...
Just don't use DB name in connection string.
"Data Source=.\SQLEXPRESS;Integrated Security=True;"
I was having the same troubles as Anshuman...
By my testing of the code in question of Anshuman there have been very simple error:
there have to be SqlConnection.ClearAllPools(); instead of SqlConnection.ClearPool(con);
Like this trouble of
"cannot drop database because is in use..."
disappears.

Categories

Resources