gpt4 book ai didi

c# - 如何在不使用 SMO 的情况下在 C# 中备份数据库 (SQL Server 2008)?

转载 作者:太空狗 更新时间:2023-10-30 00:22:05 24 4
gpt4 key购买 nike

我有这段代码,但它不起作用,但我不知道为什么?

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

问题是什么?

最佳答案

您需要将该 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");
}
}
}

关于c# - 如何在不使用 SMO 的情况下在 C# 中备份数据库 (SQL Server 2008)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2614469/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com