初学数据库备份。如何实现???
上网也查过了一些代码,如:
private void Button3_Click(object sender, System.EventArgs e)
{
//引用SQLDMO.dll,SQLDMO由Microsoft SQL Server自带的SQLDMO.dll提供,SQLDMO.dll是一个COM对象
SQLDMO.Backup backup=new SQLDMO.BackupClass();
SQLDMO.SQLServer sqlserver=new SQLDMO.SQLServerClass();
sqlserver.LoginSecure=false;
sqlserver.Connect("localhost","sa","1");
backup.Action=SQLDMO.SQLDMO_BACKUP_TYPE.SQLDMOBackup_Database;
backup.Database="userdb";
backup.Files=@"E:\Project\meng\data\userdb.bak";
backup.BackupSetName="userdb";
backup.BackupSetDescription="数据库备份";
backup.Initialize=true;
backup.SQLBackup(sqlserver);
}
不知道上面的代码是否能实现?
但上面所说到的SQLDMO.DLL这怎么引用啊?在电脑上搜索到了这个文件了,并添加到了BIN目录下,但没用。
------解决方案--------------------添加引用----COM---添加
------解决方案-------------------- public static void DbBackup()
{
SQLDMO.Backup oBackup = new SQLDMO.BackupClass();
SQLDMO.SQLServer oSQLServer = new SQLDMO.SQLServerClass();
try
{
oSQLServer.LoginSecure = false;
oSQLServer.Connect("localhost", "sa", "123456");
oBackup.Action = SQLDMO.SQLDMO_BACKUP_TYPE.SQLDMOBackup_Database;
oBackup.Database = "Northwind";
oBackup.Files = @"d:\Northwind.bak";
oBackup.BackupSetName = "Northwind";
oBackup.BackupSetDescription = "数据库备份";
oBackup.Initialize = true;
oBackup.SQLBackup(oSQLServer);
}
catch
{
throw;
}
finally
{
oSQLServer.DisConnect();
}
}
------解决方案--------------------
void backupButton_Click(object sender, System.EventArgs e)
{
string path = pathTextBox.Text;
string dbname = dbDropDownList.SelectedValue;
string backupSql = "use master;";
backupSql += "backup database @dbname to disk = @path;";
SqlCommand myCommand = new SqlCommand(backupSql, new SqlConnection(ConnStr));
myCommand.Parameters.Add("@dbname", SqlDbType.Char);
myCommand.Parameters["@dbname"].Value = dbname;
myCommand.Parameters.Add("@path", SqlDbType.Char);
myCommand.Parameters["@path"].Value = path;
try
{
myCommand.Connection.Open();
myCommand.ExecuteNonQuery();
infoLabel.Text = "备份成功";
}
catch(Exception ex)
{
infoLabel.Text = "备份失败<br>" + ex.ToString();
}
finally
{
myCommand.Connection.Close();
}
}
void restoreButton_Click(object sender, System.EventArgs e)
{
string path = pathTextBox.Text;
string dbname = dbDropDownList.SelectedValue;
string restoreSql = "use master;";
restoreSql += "restore database @dbname from disk = @path;";
SqlCommand myCommand = new SqlCommand(restoreSql, new SqlConnection(ConnStr));
myCommand.Parameters.Add("@dbname", SqlDbType.Char);
myCommand.Parameters["@dbname"].Value = dbname;
myCommand.Parameters.Add("@path", SqlDbType.Char);
myCommand.Parameters["@path"].Value = path;
try
{
myCommand.Connection.Open();
myCommand.ExecuteNonQuery();
in