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

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);
}
}

Related

creating connection string for attached MDF file

what you see bellow is a part of my WPF project I used it to backup/restore my SQL server database and it works great but; when I want to make a setup file by advanced installer and I move MDF and LDF files created by SQL script to app directory to use in SQL express it doesn't work. Now I want to know what can I do with connection string so that backup/restore prosses can work correctly
private string connectionString = "Data Source=.\\SQLEXPRESS;AttachDbFileName=|DataDirectory|\\DBNBO.mdf;Database=DBNBO; Trusted_Connection=Yes;";
private void BtnBackup_OnClick(object sender, EventArgs e)
{
SqlConnection connection = new SqlConnection(connectionString);
string database = connection.Database;
string query = "Backup Database [" + database + "] To Disk = '" + txtBackup.Text + "\\DB_backup.bak'";
SqlCommand command = new SqlCommand(query, connection);
connection.Open();
command.ExecuteNonQuery();
connection.Close();
}
private void btnRestore_Click(object sender, EventArgs e)
{
SqlConnection connection = new SqlConnection(connectionString);
string database = connection.Database;
if (connection.State != ConnectionState.Open) connection.Open();
string query1 = string.Format("Alter Database [" + database + "] Set Single_User With Rollback Immediate");
SqlCommand command1 = new SqlCommand(query1, connection);
command1.ExecuteNonQuery();
string query2 = string.Format("Use Master Restore Database [" + database + "] From Disk = '" + txtRestore.Text + "' With Replace");
SqlCommand command2 = new SqlCommand(query2, connection);
command2.ExecuteNonQuery();
string query3 = string.Format("Alter Database [" + database + "] Set Multi_User");
SqlCommand command3 = new SqlCommand(query3, connection);
command3.ExecuteNonQuery();
connection.Close();
}

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

Can't make SQL Server connection C#

I'm trying to connect to a SQL Server on a local machine, run a SQL command against it and log the results. The code keeps failing at making the connection to the server.
I can't quite see what I'm doing wrong. Everything I've searched for either doesn't apply to this method or seems to match what I'm doing. I think I have other problems in the code as well, but I can't even get past the SQL connection to test the rest. Here is my code:
string svrConnection = "Server=.\\sqlexpress;Database="+db+";User ID=user;Password=password;";
SqlConnection con;
SqlCommand cmd;
Directory.CreateDirectory("C:\\"db"\\");
FileInfo file = new FileInfo("C:\\script.sql");
string PCS = file.OpenText().ReadToEnd();
con = new SqlConnection(svrConnection);
StreamWriter PCSLog = new StreamWriter(#"C:\\" + db + "\\Log" + db + ".txt");
try
{
con.Open();
cmd = new SqlCommand(PCS, con);
cmd.ExecuteNonQuery();
using (SqlDataReader pcsrdr = cmd.ExecuteReader())
using (PCSLog)
{
while (pcsrdr.Read())
PCSLog.WriteLine(pcsrdr[0].ToString() + pcsrdr[1].ToString() + ",");
}
PCSLog.Close();
cmd.Dispose();
con.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection !", ex.Message);
}
There are additional problems with your code:
The Lines
cmd.Dispose();
con.Close();
are not guaranteed to execute if an exception occurs.
You call PCSLog.Close AFTER after you have disposed of it
I would suggest this as a better alternative (irrespective of the other comments made here).
string svrConnection = "Server=.\\sqlexpress;Database="+db+";User ID=user;Password=password;";
Directory.CreateDirectory("C:\\" + db + "\\");
FileInfo file = new FileInfo("C:\\script.sql");
string PCS = file.OpenText().ReadToEnd();
try
{
using (SqlConnection con = new SqlConnection(svrConnection))
{
con.Open();
using (SqlCommand cmd = new SqlCommand(PCS, con))
{
cmd.ExecuteNonQuery();
using (SqlDataReader pcsrdr = cmd.ExecuteReader())
using (StreamWriter PCSLog = new StreamWriter("C:\\" + db + "\\Log" + db + ".txt"))
{
while (pcsrdr.Read())
PCSLog.WriteLine(pcsrdr[0].ToString() + pcsrdr[1].ToString() + ",");
}
}
}
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection !", ex.Message);
}
I think the issue is your connection string. Try this:
string svrConnection = "Data Source=.\\SQLEXPRESS;Initial Catalog=" + db + ";User Id=user;Password=password;"
Or to get a connection using your windows credentials:
string svrConnection = "Data Source=.\\SQLEXPRESS;Initial Catalog=" + db + ";Trusted_Connection=True;"
Also, ExecuteNonQuery does not run each command separated by GO. You will need to split your query into sections and run each individually.

Data being duplicated in a database on save

I am trying to save some data in a database using an INSERT query but it is saving double value on single click. For example I save 'Lahore', it'll save it two times:
Lahore
Lahore
SqlConnection conn = new SqlConnection("Data Source = HAMAAD-PC\\SQLEXPRESS ; Initial Catalog = BloodBank; Integrated Security = SSPI ");
try
{
conn.Open();
SqlCommand query = new SqlCommand("insert into City values('" + txtCity.Text + "')", conn);
query.ExecuteNonQuery();
SqlDataReader dt = query.ExecuteReader();
if (dt.Read())
{
MessageBox.Show("Saved....!");
}
else
{
MessageBox.Show("Not saved.....");
}
}
catch (Exception ex)
{
MessageBox.Show("Failed....." + ex.Message);
}
Your code is doing exactly what you told it to.
If you call an Execute*() method twice, it will run your query twice.
It's saving twice because you are executing the query twice:
query.ExecuteNonQuery();
SqlDataReader dt = query.ExecuteReader();
You are saving twice.
The executeNonQuery will return the number of rows affected so use this instead.
SqlConnection conn = new SqlConnection("Data Source = HAMAAD-PC\\SQLEXPRESS ; Initial Catalog = BloodBank; Integrated Security = SSPI ");
try
{
conn.Open();
SqlCommand query = new SqlCommand("insert into City values('" + txtCity.Text + "')", conn);
var rowsAffected = query.ExecuteNonQuery();
if (rowsAffected == 1)
{
MessageBox.Show("Saved....!");
}
else
{
MessageBox.Show("Not saved.....");
}
}
catch (Exception ex)
{
MessageBox.Show("Failed....." + ex.Message);
}

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.

Categories