Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
.net 如何用C语言编程备份Sql数据库#_.net_Database_Sql Server 2008_C# 4.0_Backup - Fatal编程技术网

.net 如何用C语言编程备份Sql数据库#

.net 如何用C语言编程备份Sql数据库#,.net,database,sql-server-2008,c#-4.0,backup,.net,Database,Sql Server 2008,C# 4.0,Backup,我想用.NET4框架中的C#编写一段代码来备份我的SQLServer2008数据库。任何人都可以提供帮助。您可以使用SqlConnection和SqlCommand连接到数据库,并执行以下命令文本,例如: BACKUP DATABASE [MyDatabase] TO DISK = 'C:\....\MyDatabase.bak' 有关示例,请参见。以下内容解释了有关如何使用c语言支持sql server 2008数据库的完整详细信息# Sql数据库备份可以使用多种方法完成。您可以像在另一个

我想用.NET4框架中的C#编写一段代码来备份我的SQLServer2008数据库。任何人都可以提供帮助。

您可以使用SqlConnection和SqlCommand连接到数据库,并执行以下命令文本,例如:

BACKUP DATABASE [MyDatabase] TO  DISK = 'C:\....\MyDatabase.bak'
有关示例,请参见。

以下内容解释了有关如何使用c语言支持sql server 2008数据库的完整详细信息#

Sql数据库备份可以使用多种方法完成。您可以像在另一个答案中一样使用Sql命令,也可以创建自己的类来备份数据

但这是不同的备份模式

  • 完全数据库备份
  • 差异数据库备份
  • 事务日志备份
  • 压缩备份

  • 但是,这种方法的缺点是需要在客户端系统上安装sql management studio。

    最好使用如下配置文件:

    <?xml version="1.0" encoding="utf-8"?>
    <configuration>
      <connectionStrings>
        <add name="MyConnString" connectionString="Data Source=(local);Initial Catalog=MyDB; Integrated Security=SSPI" ;Timeout=30"/>
      </connectionStrings>
      <appSettings>
        <add key="BackupFolder" value="C:/temp/"/>
      </appSettings>
    </configuration> 
    
    // read connectionstring from config file
    var connectionString = ConfigurationManager.ConnectionStrings["MyConnString"].ConnectionString; 
    
    // read backup folder from config file ("C:/temp/")
    var backupFolder = ConfigurationManager.AppSettings["BackupFolder"];
    
    var sqlConStrBuilder = new SqlConnectionStringBuilder(connectionString);
    
    // set backupfilename (you will get something like: "C:/temp/MyDatabase-2013-12-07.bak")
    var backupFileName = String.Format("{0}{1}-{2}.bak", 
        backupFolder, sqlConStrBuilder.InitialCatalog, 
        DateTime.Now.ToString("yyyy-MM-dd"));
    
    using (var connection = new SqlConnection(sqlConStrBuilder.ConnectionString))
    {
        var query = String.Format("BACKUP DATABASE {0} TO DISK='{1}'", 
            sqlConStrBuilder.InitialCatalog, backupFileName);
    
        using (var command = new SqlCommand(query, connection))
        {
            connection.Open();
            command.ExecuteNonQuery();
        }
    }
    
    为我工作:

    public class BackupService
    {
        private readonly string _connectionString;
        private readonly string _backupFolderFullPath;
        private readonly string[] _systemDatabaseNames = { "master", "tempdb", "model", "msdb" };
    
        public BackupService(string connectionString, string backupFolderFullPath)
        {
            _connectionString = connectionString;
            _backupFolderFullPath = backupFolderFullPath;
        }
    
        public void BackupAllUserDatabases()
        {
            foreach (string databaseName in GetAllUserDatabases())
            {
                BackupDatabase(databaseName);
            }
        }
    
        public void BackupDatabase(string databaseName)
        {
            string filePath = BuildBackupPathWithFilename(databaseName);
    
            using (var connection = new SqlConnection(_connectionString))
            {
                var query = String.Format("BACKUP DATABASE [{0}] TO DISK='{1}'", databaseName, filePath);
    
                using (var command = new SqlCommand(query, connection))
                {
                    connection.Open();
                    command.ExecuteNonQuery();
                }
            }
        }
    
        private IEnumerable<string> GetAllUserDatabases()
        {
            var databases = new List<String>();
    
            DataTable databasesTable;
    
            using (var connection = new SqlConnection(_connectionString))
            {
                connection.Open();
    
                databasesTable = connection.GetSchema("Databases");
    
                connection.Close();
            }
    
            foreach (DataRow row in databasesTable.Rows)
            {
                string databaseName = row["database_name"].ToString();
    
                if (_systemDatabaseNames.Contains(databaseName))
                    continue;
    
                databases.Add(databaseName);
            }
    
            return databases;
        }
    
        private string BuildBackupPathWithFilename(string databaseName)
        {
            string filename = string.Format("{0}-{1}.bak", databaseName, DateTime.Now.ToString("yyyy-MM-dd"));
    
            return Path.Combine(_backupFolderFullPath, filename);
        }
    }
    
    公共类备份服务
    {
    私有只读字符串_connectionString;
    私有只读字符串_backupFolderFullPath;
    私有只读字符串[]\u systemDatabaseNames={“master”、“tempdb”、“model”、“msdb”};
    公共备份服务(字符串连接字符串、字符串备份文件夹完整路径)
    {
    _connectionString=connectionString;
    _backupFolderFullPath=backupFolderFullPath;
    }
    public void BackupAllUserDatabases()
    {
    foreach(GetAllUserDatabases()中的字符串databaseName)
    {
    BackUpdatebase(数据库名称);
    }
    }
    public void backupdatebase(字符串数据库名)
    {
    字符串filePath=BuildBackupPathWithFilename(数据库名);
    使用(var connection=newsqlconnection(_connectionString))
    {
    var query=String.Format(“将数据库[{0}]备份到磁盘='{1}',数据库名,文件路径);
    使用(var命令=新的SqlCommand(查询、连接))
    {
    connection.Open();
    command.ExecuteNonQuery();
    }
    }
    }
    私有IEnumerable GetAllUserDatabases()
    {
    var databases=newlist();
    数据表数据库稳定;
    使用(var connection=newsqlconnection(_connectionString))
    {
    connection.Open();
    databasesTable=connection.GetSchema(“数据库”);
    connection.Close();
    }
    foreach(databasesTable.Rows中的DataRow行)
    {
    字符串databaseName=行[“数据库名称”]。ToString();
    if(_systemDatabaseNames.Contains(databaseName))
    继续;
    databases.Add(databaseName);
    }
    返回数据库;
    }
    私有字符串BuildBackupPathWithFilename(字符串数据库名)
    {
    string filename=string.Format(“{0}-{1}.bak”,databaseName,DateTime.Now.ToString(“yyyy-MM-dd”);
    返回路径.Combine(_backupFolderFullPath,filename);
    }
    }
    
    您可以使用以下查询进行备份和还原,您必须更改备份路径

    数据库名称=[数据]

    备份:

    BACKUP DATABASE [data] TO  DISK = N'C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\Backup\data.bak' WITH NOFORMAT, NOINIT,  NAME = N'data-Full Database Backup', SKIP, NOREWIND, NOUNLOAD,  STATS = 10
    GO
    
    恢复:

    RESTORE DATABASE [data] FROM  DISK = N'C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\Backup\data.bak' WITH  FILE = 1,  NOUNLOAD,  REPLACE,  STATS = 10
    GO
    
    SqlConnection con=newsqlconnection();
    SqlCommand sqlcmd=新的SqlCommand();
    SqlDataAdapter da=新的SqlDataAdapter();
    DataTable dt=新的DataTable();
    con.ConnectionString=ConfigurationManager.ConnectionString[“MyConString”]。ConnectionString;
    字符串backupDIR=“~/BackupDB”;
    字符串路径=Server.MapPath(backupDIR);
    尝试
    {
    var databaseName=“MyFirstDatabase”;
    con.Open();
    string saveFileName=“HiteshBackup”;
    sqlcmd=new-SqlCommand(“备份数据库”+databaseName.BKSDatabaseName+“到磁盘=”“+path+“\\”+saveFileName+”.Bak',con);
    sqlcmd.ExecuteNonQuery();
    con.Close();
    ViewBag.Success=“备份数据库成功”;
    返回视图(“创建”);
    }
    捕获(例外情况除外)
    {
    ViewBag.Error=“数据库备份过程中发生错误!
    ”+ex.ToString(); 返回视图(“创建”); }
    这对我很有效

    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;
        }
    }
    
    private void BackupManager\u加载(对象发送方,事件参数e)
    {
    txtFileName.Text=“DB_Backup_uu”+DateTime.Now.ToString(“dd-MMM-yy”);
    }
    私有无效btnDBBackup_单击(对象发送者,事件参数e)
    {
    如果(!string.IsNullOrEmpty(txtFileName.Text.Trim()))
    {
    备份();
    }
    其他的
    {
    MessageBox.Show(“请输入备份文件名”,MessageBoxButtons.OK,MessageBoxIcon.Information);
    txtFileName.Focus();
    返回;
    }
    }
    私有无效备份()
    {
    尝试
    {
    progressBar1.值=0;
    对于(progressBar1.Value=0;progressBar1.Value<100;progressBar1.Value++)
    {
    }
    pl.DbName=“Inventry”;
    pl.Path=@“D:/”+txtFileName.Text.Trim()+“.bak”;
    对于(progressBar1.Value=100;progressBar1.Value<200;progressBar1.Value++)
    {
    }
    bl.DbBackUp(pl);
    对于(progressBar1.Value=200;progressBar1.Value<300;progressBar1.Value++)
    {
    }
    对于(progressBar1.Value=300;progressBar1.Value<400;progressBar1.Value++)
    {
    }
    对于(progressBar1.Value=400;progressBar1.Valueprivate 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;
        }
    }
    
     private void BackupManager_Load(object sender, EventArgs e)
            {
                txtFileName.Text = "DB_Backup_" + DateTime.Now.ToString("dd-MMM-yy");
            }
    
            private void btnDBBackup_Click(object sender, EventArgs e)
            {
                if (!string.IsNullOrEmpty(txtFileName.Text.Trim()))
                {
                    BackUp();
                }
                else
                {
                    MessageBox.Show("Please Enter Backup File Name", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    txtFileName.Focus();
                    return;
                }
            }
    
            private void BackUp()
            {
                try
                {
    
                    progressBar1.Value = 0;
    
                    for (progressBar1.Value = 0; progressBar1.Value < 100; progressBar1.Value++)
                    {
    
                    }
    
                    pl.DbName = "Inventry";
                    pl.Path = @"D:/" + txtFileName.Text.Trim() + ".bak";
    
                    for (progressBar1.Value = 100; progressBar1.Value < 200; progressBar1.Value++)
                    {
    
                    }
    
                    bl.DbBackUp(pl);
                    for (progressBar1.Value = 200; progressBar1.Value < 300; progressBar1.Value++)
                    {
    
                    }
    
                    for (progressBar1.Value = 300; progressBar1.Value < 400; progressBar1.Value++)
                    {
    
                    }
    
                    for (progressBar1.Value = 400; progressBar1.Value < progressBar1.Maximum; progressBar1.Value++)
                    {
    
                    }
                    if (progressBar1.Value == progressBar1.Maximum)
                    {
                        MessageBox.Show("Backup Saved Successfully...!!!", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    else
                    {
                        MessageBox.Show("Action Failed, Please try again later", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
    
                catch (Exception ex)
                {
                    MessageBox.Show("Action Failed, Please try again later", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                finally
                {
                    progressBar1.Value = 0;
                }
            }
    
    SqlCmd -E -S Server_Name –Q “BACKUP DATABASE [Name_of_Database] TO DISK=’X:PathToBackupLocation[Name_of_Database].bak'”
    
    SqlCmd -E -S Server_Name –Q “RESTORE DATABASE [Name_of_Database] FROM DISK=’X:PathToBackupFile[File_Name].bak'”
    
            FileInfo file = new FileInfo("DB\\batfile.bat");
            Process process = new Process();
            process.StartInfo.FileName = file.FullName;
            process.StartInfo.Arguments = @"-X";
            process.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
            process.StartInfo.UseShellExecute = false; //Changed Line
            process.StartInfo.RedirectStandardOutput = true;  //Changed Line
            process.Start();
            string output = process.StandardOutput.ReadToEnd(); //Changed Line
            process.WaitForExit(); //Moved Line
    
    public void BackupDatabase(string databaseName, string userName, string password, string serverName, string destinationPath)
    
     {  
    //Define a Backup object variable.
    Backup sqlBackup = new Backup();
    //Specify the type of backup, the description, the name, and the database to be backed up.
    sqlBackup.Action = BackupActionType.Database;
    
    sqlBackup.BackupSetDescription = "BackUp of:" + databaseName + "on" + DateTime.Now.ToShortDateString();
    
    sqlBackup.BackupSetName = "FullBackUp";
    
    sqlBackup.Database = databaseName;
    //Declare a BackupDeviceItem
    BackupDeviceItem deviceItem = new BackupDeviceItem(destinationPath + "FullBackUp.bak", DeviceType.File);
    
    //Define Server connection
    ServerConnection connection = new ServerConnection(serverName, userName, password); //To Avoid TimeOut Exception
    Server sqlServer = new Server(connection);
    sqlServer.ConnectionContext.StatementTimeout = 60 * 60;
    Database db = sqlServer.Databases[databaseName];
    (Reference Database As microsoft.sqlserver.management.smo.database, not as System.entity.database)
    
    sqlBackup.Initialize = true;
    
    sqlBackup.Checksum = true;
    
    sqlBackup.ContinueAfterError = true;
    //Add the device to the Backup object.
    sqlBackup.Devices.Add(deviceItem);
    
    //Set the Incremental property to False to specify that this is a full database backup. 
    sqlBackup.Incremental = false;
    sqlBackup.ExpirationDate = DateTime.Now.AddDays(3);
    
    //Specify that the log must be truncated after the backup is complete.        
    sqlBackup.LogTruncation = BackupTruncateLogType.Truncate;
    sqlBackup.FormatMedia = false;
    
    //Run SqlBackup to perform the full database backup on the instance of SQL Server. 
    sqlBackup.SqlBackup(sqlServer);
    
    //Remove the backup device from the Backup object.           
     sqlBackup.Devices.Remove(deviceItem);
    
    }
    
    Microsoft.SqlServer.ConnectionInfo
    Microsoft.SqlServer.Management.Sdk.Sfc
    Microsoft.SqlServer.Smo
    Microsoft.SqlServer.SmoExtended
    Microsoft.SqlServer.SqlEnum