繁体   English   中英

ServerConnection 不适用于连接字符串

[英]ServerConnection doesn't work with a connection string

我使用下面的代码在 c#.net 中从我的数据库创建备份。 但是当我运行代码时,我收到此错误:

无法连接到服务器 Data Source=.;Initial Catalog=AngularJs;Integrated Security=True。

我这样做的代码是:

ServerConnection con = new ServerConnection("Data Source=" + txtServerName.Text + ";Initial Catalog=" + drpDatabases.SelectedItem.ToString() + ";Integrated Security=True");
        Server server = new Server(con);
        Backup source = new Backup();
        source.Action = BackupActionType.Database;
        source.Database = drpDatabases.SelectedItem.ToString();
        BackupDeviceItem destination = new BackupDeviceItem(Path, DeviceType.File);
        source.Devices.Add(destination);
        source.SqlBackup(server);
        con.Disconnect();

问题在哪里? 为什么这不起作用? 我用 sqlconnection 测试了连接字符串,它工作正常并且打开得很好。

您的代码有误,请使用:

ServerConnection con = new ServerConnection(
   new SqlConnection(
       "Data Source=" + txtServerName.Text + ";Initial Catalog=" 
       + drpDatabases.SelectedItem.ToString() 
       + ";Integrated Security=True")); 

ServerConnection(string)重载需要一个实例名称,而不是一个连接字符串。 您可以简单地编写new ServerConnection(".")或:

var con = new ServerConnection(txtServerName.Text);

该错误消息告诉您ServerConnection尝试连接到名称与整个连接字符串相同的服务器,但失败了。

ServerConnection 表示到特定服务器的连接,而不是数据库,因此它不需要 SqlConnection 对象。 如果您提供一个,它仅用于提取相关信息。

尝试这个:

SqlConnection con = new SqlConnection("Data Source=" + txtServerName.Text + ";Initial Catalog=" + drpDatabases.SelectedItem.ToString() + ";Integrated Security=True");
SeverConnection scon = new ServerConnection(con);
Server svr = new Server(scon);

因为我认为您为 ServerConnection 传递了错误的参数。

尝试这个:

ServerConnection con= new ServerConnection(new SqlConnectionStringBuilder(cnstring).DataSource);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM