//引入必要的命名空间 using System; using System.IO; using System.Data.SqlClient; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms;

namespace SQLBackupTool { //定义备份类 public class SQLBackup { //定义私有成员变量 private string serverName; private string databaseName; private string backupPath; private string backupFileName; private string userName; private string password; private bool isCompressed;

    //定义构造函数
    public SQLBackup(string serverName, string databaseName, string backupPath, string backupFileName, string userName, string password, bool isCompressed)
    {
        this.serverName = serverName;
        this.databaseName = databaseName;
        this.backupPath = backupPath;
        this.backupFileName = backupFileName;
        this.userName = userName;
        this.password = password;
        this.isCompressed = isCompressed;
    }

    //定义备份方法
    public void Backup()
    {
        try
        {
            //创建连接字符串
            string connectionString = "Server=" + serverName + ";Database=" + databaseName + ";User ID=" + userName + ";Password=" + password + ";";

            //创建连接对象
            SqlConnection connection = new SqlConnection(connectionString);

            //打开连接
            connection.Open();

            //创建备份命令
            string backupCommand = "BACKUP DATABASE " + databaseName + " TO DISK='" + backupPath + "\\" + backupFileName + "'";

            //判断是否需要压缩备份文件
            if (isCompressed)
            {
                backupCommand += " WITH COMPRESSION";
            }

            //创建备份对象
            SqlCommand command = new SqlCommand(backupCommand, connection);

            //执行备份命令
            command.ExecuteNonQuery();

            //关闭连接
            connection.Close();

            //提示备份成功
            MessageBox.Show("Backup completed successfully.");
        }
        catch (Exception ex)
        {
            //提示备份失败
            MessageBox.Show("Backup failed: " + ex.Message);
        }
    }
}

}

//使用方法 //实例化备份对象 SQLBackup backup = new SQLBackup("localhost", "mydatabase", "D:\backup", "mydatabase.bak", "sa", "password", true);

//调用备份方法 backup.Backup();

使用c#开发一个类似于SQLBackupAndFTP的工具并且带注释

原文地址: http://www.cveoy.top/t/topic/LTg 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录