0

I want to backup my DB but I got a error:

ConnectionStrings cannot be used like a method

How can I resolve this?

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();
}
4

2 回答 2

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
于 2013-03-11T08:09:37.687 回答
0

ConnectionStrings是一个集合。它必须像这样使用:

ConfigurationManager.Connectionstrings[0].ConnectionString
于 2013-03-11T08:06:54.153 回答