Set database backup file on local machine - c#

POSSIBLE DUPLICATE OF :
How to create SQL Server 2008 database full backup programmatically in desired folder
I have a database on my computer (SQL Server 2008 Express).
I need any sample code in C# that I can use to backup the database to a file using Visual Studio 2010.
Thanks..
i'll using this code to connect Database
public SqlConnection SqlSaverConn()
{
string path = Application.StartupPath + "\\";
String conStr = #"Data Source=.\SQLEXPRESS;AttachDbFilename="+ path +"SMS_DB.mdf;Integrated Security=True;User Instance=True";
SqlConnection con = new SqlConnection(conStr);
try
{
con.Open();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
return con;
}

Just execute SQL Server command
BACKUP DATABASE database_name TO DISK='d:\path\to\backup\file\on\the\server.bak'
from your program
EDIT
public SqlConnection SqlSaverConn()
{
string path = Application.StartupPath + "\\";
String conStr = #"Data Source=.\SQLEXPRESS;AttachDbFilename="+ path +"SMS_DB.mdf;
Integrated Security=True; User Instance=True";
SqlConnection con = new SqlConnection(conStr);
try
{
con.Open();
SqlCommand command;
command = new SqlCommand(#"backup database SMS_DB.mdf to disk ='" + path + "\\" + name, con);
command.ExecuteNonQuery();
MessageBox.Show("Backup Created.");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
return con;
}
Try this peice of code.

Im using flowing code to connect database
public SqlConnection SqlSaverConn()
{
string path = Application.StartupPath + "\\";
String conStr = #"Data Source=.\SQLEXPRESS;AttachDbFilename="+ path +"SMS_DB.mdf;Integrated Security=True;User Instance=True";
SqlConnection con = new SqlConnection(conStr);
try
{
con.Open();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
return con;
}
can i use your SQL Command to set backup using upon type connection

This what I did and it Worked!
private void BackupButtonClick(object sender, RoutedEventArgs e)
{
// FILE NAME WITH DATE DISTICNTION
string fileName = string.Format("SchoolBackup_{0}.bak", DateTime.Now.ToString("yyyy_MM_dd_h_mm_tt"));
try
{
// YOUR SEREVER OR MACHINE NAME
Server dbServer = new Server (new ServerConnection("DESKTOP"));
Microsoft.SqlServer.Management.Smo.Backup dbBackup = new Microsoft.SqlServer.Management.Smo.Backup()
{
Action = BackupActionType.Database,
Database = "School"
};
dbBackup.Devices.AddDevice(#backupDirectory() +"\\"+ fileName, DeviceType.File);
dbBackup.Initialize = true;
dbBackup.SqlBackupAsync(dbServer);
MessageBox.Show("Backup", "Backup Completed!");
}
catch(Exception err)
{
System.Windows.MessageBox.Show(err.ToString());
}
}
// THE DIRECTOTRY YOU WANT TO SAVE IN
public string backupDirectory()
{
using (var dialog = new FolderBrowserDialog())
{
var result = dialog.ShowDialog();
return dialog.SelectedPath;
}
}

Related

I'm trying to restore a SQL Server database backup with this code :

I'm trying to restore a SQL Server database backup with this code:
private void restoreButton_Click(object sender, EventArgs e)
{
string database = con.Database.ToString();
if (con.State != ConnectionState.Open)
{
con.Open();
}
try
{
string sqlStmt2 = string.Format("ALTER [MangementSystemBD] [" + database + "] SET SINGLE_USER WITH ROLLBACK IMMEDIATE");
SqlCommand bu2 = new SqlCommand(sqlStmt2, con);
bu2.ExecuteNonQuery();
string sqlStmt3 = "USE MASTER RESTORE [MangementSystemBD] [" + database + "] FROM DISK='" + textBox2.Text + "'WITH REPLACE;";
SqlCommand bu3 = new SqlCommand(sqlStmt3, con);
bu3.ExecuteNonQuery();
string sqlStmt4 = string.Format("ALTER [MangementSystemBD] [" + database + "] SET MULTI_USER");
SqlCommand bu4 = new SqlCommand(sqlStmt4, con);
bu4.ExecuteNonQuery();
MessageBox.Show("database restoration done successfully");
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
But when I execute it I get this error:
For restoring database use this code
public void RestoreDatabaseBackup()
{
ExecuteQuery("EXEC msdb.dbo.sp_delete_database_backuphistory #database_name = 'DatabaseName");
ExecuteQuery("USE MASTER");
OpenFileDialog res = new OpenFileDialog();
res.ShowDialog();
if (res.FileName.ToString() == "")
{
//MessageBox.Show("Select Valid .bak File");
}
else
{
try
{
string s = res.FileName.ToString();
SqlConnection sqlConnection = new SqlConnection(#"Data Source=ServerName;Initial Catalog=yourDatabaseName;Integrated Security=True;Pooling=False");
if (sqlConnection.State == System.Data.ConnectionState.Open)
{
sqlConnection.Close();
}
sqlConnection.Open();
ServerConnection ServerConnection = new ServerConnection(sqlConnection);
Server srv = new Server(ServerConnection);
//Declare a BackupDeviceItem by supplying the backup device file name in the constructor, and the type of device is a file.
BackupDeviceItem bdi = default(BackupDeviceItem);
bdi = new BackupDeviceItem(s, DeviceType.File);
// Define a Restore object variable.
Restore rs = new Restore();
//Set the NoRecovery property to true, so the transactions are not recovered.
rs.NoRecovery = true;
rs.ReplaceDatabase = true;
// Add the device that contains the full database backup to the Restore object.
rs.Devices.Add(bdi);
rs.NoRecovery = false;
// Specify the database name.
rs.Database = sqlConnection.Database.ToString();
// Restore the full database backup with no recovery.
sqlConnection.ChangeDatabase("master");
rs.SqlRestore(srv);
// Inform the user that the Full Database Restore is complete.
srv = null;
MessageBox.Show("Database Restore complete.");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
ExecuteQuery is a normal method to run SQL you should make it

Backup SQL Server 2014 DB in c# not work

I create a program to backup the whole DB from SQL server 2014 , i used the code before it was work perfectly on another laptop (was working on it coding with c#).
now i'm trying to backup not work at all this is the code:
1/- SqlConnection:
SqlConnection con = new SqlConnection(WindowsFormsApplication11.Properties.Settings.Default.database1ConnectionString);
2/- textbtn1
private void browseButton_Click(object sender, EventArgs e)
{
FolderBrowserDialog dlg = new FolderBrowserDialog();
if (dlg.ShowDialog() == DialogResult.OK)
{
textBox1.Text = dlg.SelectedPath;
BackupButton.Enabled = true;
}
}
3/- textbtn2 code :
private void BackupButton_Click(object sender, EventArgs e)
{
string database = con.Database.ToString();
try
{
if(textBox1.Text==string.Empty)
{
MessageBox.Show("please enter backup file location");
}
else
{
string cmd = "BACKUP DATABASE [" + database + "] TO DISK='" + textBox1.Text + "\\" + "database" + "-" + DateTime.Now.ToString("yyyy-MM-dd--HH-mm-ss") + ".bak'";
using(SqlCommand command = new SqlCommand(cmd,con))
{
if(con.State!=ConnectionState.Open)
{
con.Open();
}
command.ExecuteNonQuery();
con.Close();
MessageBox.Show("database backup done successefully");
BackupButton.Enabled = false;
}
}
}
catch
{
}
}
** even this code not work and no message show up :p , don't know why ?
i changed every thing , i created a new class called DBconnect :
class DBconnect
{
public SqlConnection myConn = new SqlConnection(#"Data Source=MYSERVERNAME;Initial Catalog=MYDBNAME;User ID=sa;Password=12345");
public void backup(string name_path)
{
try
{
string query = "Backup Database MYDBNAMEto Disk ='" + name_path + ".bak'";
SqlCommand myCommand = new SqlCommand();
myCommand.CommandText = query;
myCommand.Connection = myConn;
myCommand.ExecuteNonQuery();
MessageBox.Show("sauvegarde succès", "sauvegarde", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception exp)
{
MessageBox.Show(exp.Message);
}
}
}
}
in my form i did this :
DBconnect conn = new DBconnect();
in backup textbtn2 i did this :
string Namefile = textboxBATH.Text + "\\MYDBNAME" + " " + DateTime.Now.ToShortDateString().Replace('/', '-') + "-" + DateTime.Now.ToLongTimeString().Replace(':', '-');
Conn.backup(Namefile);
in this case i faces this erorr message :
Cannot open backup device. Operating system error 5(Access is denied.) BACKUP DATABASE is terminating abnormally.
i thought SQL service might not have permission to the Path where backup bath is supposed to be created . and i create new folder in my Desktop and gave it the permission Read+Write .. and this not work too .. :p
thank you all .

WPF Install Setup and Deployment and sql Script file

I'm currently developing a small WPF application.
I generate sql script file that contains commands to create database and tables, views, procedures and so on.
But where in my wpf code I must put this script or how to read the sql script file during first run and create database and tables? Other if the client choose a diferente folder and directory to install the application how to get a path of sql script file? I use Visual Studio Installer.
void excuteScript()
{
String connString = #"Data Source=.\sqlexpress;Initial Catalog=master;Integrated Security=True";
String cmdText = "select * from master.dbo.sysdatabases where name= 'Teste'";
Boolean bRet;
SqlConnection sqlConnection = new SqlConnection(connString);
SqlCommand sqlCmd = new SqlCommand(cmdText, sqlConnection);
try
{
sqlConnection.Open();
SqlDataReader reader = sqlCmd.ExecuteReader();
bRet = reader.HasRows;
sqlConnection.Close();
}
catch (Exception e)
{
bRet = false;
sqlConnection.Close();
MessageBox.Show(e.Message);
}
if (bRet == true)
{
}
else
{
string sqlConnectionString = "Data Source=(local);Initial Catalog=master;Integrated Security=True";
var file = new FileInfo(System.IO.Path.Combine(System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), #"teste.sql"));
string script = file.OpenText().ReadToEnd();
SqlConnection conn = new SqlConnection(sqlConnectionString);
Server server = new Server(new ServerConnection(conn));
server.ConnectionContext.ExecuteNonQuery(script);
}
}

Connection string and sql backup

I'm having problem with the following C# code to perform a backup, particularly in the connection string.
The code is as follows:
private void BK()
{
string strconn = #"Data Source=.\SQLEXPRESS; AttachDbFilename=|DataDirectory|\db.mdf;Integrated Security=True;User Instance=True";
SqlConnection conn = new SqlConnection();
conn.ConnectionString = strconn;
try {
//Query per backup
string queryBK = "BACKUP DATABASE db TO DISK ='C:\\Program Files\\Microsoft SQLServer\\MSSQL10.SQLEXPRESS\\MSSQL\\Backup\\db.bak' WITH INIT, SKIP, CHECKSUM";
SqlCommand cmdBK = new SqlCommand(queryBK, conn);
conn.Open();
cmdBK.ExecuteNonQuery();
MessageBox.Show("backup effettuato");
}
catch (Exception ex) {
MessageBox.Show(ex.Message, "ERRORE", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally {
conn.Close();
}
}
This code works on the development PC, but if I install my application on another PC it throws this error:
The database does not exist. Verify that the name has been entered
correctly. INTERRUPTION ANOMALOUS BACKUP DATABASE.
I would stress that this string works well with the operations INSERT, DELETE, UPDATE
on both my PC and on the PC test.
If I replace the connection string with:
string strconn = #"Data Source=.\SQLEXPRESS; Database = db;Trusted_Connection =True";
The string works on my dev machine but not on the test machine. It throws the following error:
Can not open database requested by the login. Login failed. Login
failed for user Pina-PC \ Pina
Dear fellow you can use your code in this way.
private void BK()
{
string strconn = #"Data Source=.\SQLEXPRESS; AttachDbFilename=|DataDirectory|\db.mdf;Integrated Security=True;User Instance=True";
SqlConnection conn = new SqlConnection();
conn.ConnectionString = strconn;
try {
// First get the db name
conn.Open();
string dbname;
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
dbname = cmd.Connection.Database.ToString();
//Query per backup
string queryBK = "BACKUP DATABASE " + dbname + " TO DISK ='C:\\Program Files\\Microsoft SQLServer\\MSSQL10.SQLEXPRESS\\MSSQL\\Backup\\db.bak' WITH INIT, SKIP, CHECKSUM";
SqlCommand cmdBK = new SqlCommand(queryBK, conn);
conn.Open();
cmdBK.ExecuteNonQuery();
MessageBox.Show("backup effettuato");
}
catch (Exception ex) {
MessageBox.Show(ex.Message, "ERRORE", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally {
conn.Close();
}
}
this routine will work in your case.

How to backup database (SQL Server 2008) in C# without using SMO?

I have this code and it is not working but I don't why?
try
{
saveFileDialog1.Filter = "SQL Server database backup files|*.bak";
saveFileDialog1.Title = "Database Backup";
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
SqlCommand bu2 = new SqlCommand();
SqlConnection s = new SqlConnection("Data Source=M1-PC;Initial Catalog=master;Integrated Security=True;Pooling=False");
bu2.CommandText = String.Format("BACKUP DATABASE LA TO DISK='{0}'", saveFileDialog1.FileName);
s.Open();
bu2.ExecuteNonQuery();
s.Close();
MessageBox.Show("ok");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
and I get this error :
What is the problem?
You need to assign that SqlConnection object to the SqlCommand - try this code:
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
string connStr = "Data Source=M1-PC;Initial Catalog=master;Integrated Security=True;Pooling=False";
using(SqlConnection conn = new SqlConnection(connStr))
{
string sqlStmt = String.Format("BACKUP DATABASE LA TO DISK='{0}'", saveFileDialog1.FileName);
using(SqlCommand bu2 = new SqlCommand(sqlStmt, conn))
{
conn.Open();
bu2.ExecuteNonQuery();
conn.Close();
MessageBox.Show("ok");
}
}
}
You never tell your SqlCommand which connection to use (this is what the error message says by the way, did you read it?). Either set the Connection property or use SqlConnection.CreateCommand to create the command in the first place.
Backup Sql Server 2008 database in C#(100% correct)
using System.Data.SqlClient;
try{
SqlConnection con = new SqlConnection(cs.conn());
string database = con.Database.ToString();
string datasource = con.DataSource.ToString();
string connection = con.ConnectionString.ToString();
string file_name =data_loaction+database_name;
--- "D:\\Hotel BackUp\\" + database + day + month + year + hour + minute + second + ms + ".bak";
con.Close();
con.Open();
string str = "Backup Database [" + database + "] To Disk =N'" + file_name + "'";// With Format;' + char(13),'') From Master..Sysdatabases Where [Name] Not In ('tempdb','master','model','msdb') and databasepropertyex ([Name],'Status') = 'online'";
SqlCommand cmd1 = new SqlCommand(str, con);
int s1 = cmd1.ExecuteNonQuery();
con.Close();
if (s1 >= -1)
MessageBox.Show("Database Backup Sucessfull.", "Hotel Management", MessageBoxButtons.OK, MessageBoxIcon.Information);
else{
MessageBox.Show("Database Backup Not Sucessfull.", "Hotel Management", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}

Categories