备份数据库

时间:2013-03-11 08:04:01

标签: c# asp.net database backup

我想备份我的数据库但是我收到了一个错误:

  

ConnectionStrings不能像方法一样使用

我该如何解决这个问题?

string strCon = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True";
string sSQL = "BACKUP DATABASE Database TO DISK = 'D:\\Database.bak';";
using (SqlConnection connection = new SqlConnection(ConfigurationManager.Connectionstrings(strCon).ConnectionString)) 
{
    SqlCommand command = new SqlCommand(sSQL, connection);
    connection.Open();
    command.ExecuteNonQuery();
}

2 个答案:

答案 0 :(得分:1)

您应该直接使用该变量,因为SqlConnection需要包含连接字符串的字符串对象,并且您将其存储在字符串对象本身中。

所以它就像这样:

using (SqlConnection connection = new SqlConnection(strCon)) 
{
    SqlCommand command = new SqlCommand(sSQL, connection);
    connection.Open();
    command.ExecuteNonQuery();
}

推荐:(将其存储在Web.config

<connectionStrings>
        <add name="job" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True" />
</connectionStrings>

然后像这样访问:(using System.Configuration;

ConfigurationManager.ConnectionStrings["job"].ConnectionString

答案 1 :(得分:0)

ConnectionStrings是一个集合。它必须像:

一样使用
ConfigurationManager.Connectionstrings[0].ConnectionString