2010-04-10 87 views
4

我有這個代碼,它不工作,但我不是爲什麼?如何在不使用SMO的情況下在C#中備份數據庫(SQL Server 2008)?

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

,我得到這個錯誤:

alt text http://i39.tinypic.com/2zhh34k.png

問題是什麼?

回答

4

你需要分配一個SqlConnection對象給SqlCommand - 試試這個代碼:當我使用

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"); 
     } 
    } 
} 
+0

您代碼我得到這個錯誤信息,http://i44.tinypic.com/5mbhxx.png - 什麼是proplem? – Saleh 2010-04-11 19:17:24

+2

那麼,你的SQL Server真的有一個目錄'C:\ Users \ Saleh \ Documents'?請記住:備份將在SQL Server計算機上完成** - 它不會**您自己的本地PC! – 2010-04-11 20:17:31

5

你永遠不知道你的SqlCommand要使用的連接(這是錯誤信息的方式說什麼,你看過嗎?)。要麼設置Connection屬性,要麼使用SqlConnection.CreateCommand首先創建命令。

0

備份SQL Server 2008數據庫的C#(100%正確的)

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

這已經有一個可接受的答案,你的似乎沒有添加任何東西。 – JamesT 2015-02-04 11:01:21

+0

從來沒有說過一段代碼是** 100%正確**!它或者是錯的,或者你會對它不滿...... – tugberk 2015-12-24 19:54:53

相關問題