连接数据源之间的选择 C#
我的表单上有一个 dataAdapter、dataSet 和 BindingSource,用于连接到 SQL 数据库以显示表单中的数据,一切正常。但是,我需要有两个连接服务器的选项。 例如 ISSP\SQLEXPRESS 和 MY-WEB。 我不知道该怎么做,想知道是否有人可以给我一些帮助,从哪里开始?谢谢 :) 但是当使用变量时它说它无法连接。
我正在使用下面的代码,但它说它无法连接,所以我想知道我是否引用了错误的变量?
sqlConnectionNW.ConnectionString = "Data Source=@server;Initial Catalog=Northwind;Integrated Security=True";
当我将代码更改为以下内容时,它可以完美运行。
sqlConnectionNW.ConnectionString = "Data Source=ISSP\SQLEXPRESS;Initial Catalog=Northwind;Integrated Security=True";
I've got a dataAdapter, dataSet and BindingSource on my forms to connect to an SQL database to show the data in the form, and it all works fine. However, I need to have 2 options of what server to connect to.
e.g ISSP\SQLEXPRESS and MY-WEB.
I don't know how to do this and wondered whether anyone could give me some help on where to start? Thanks :)
But when using the variables it says that it can't connect.
I'm using the code below but it says that it can't connect, so i'm wondering whether i'm refering to the variable wrong?
sqlConnectionNW.ConnectionString = "Data Source=@server;Initial Catalog=Northwind;Integrated Security=True";
When I change the code to the following, it works perfectly.
sqlConnectionNW.ConnectionString = "Data Source=ISSP\SQLEXPRESS;Initial Catalog=Northwind;Integrated Security=True";
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
首先将两个连接设置添加到您的应用程序配置文件中:
在您的应用程序中,将一个组合框添加到表单中(在本例中称为 uiConnection),然后添加以下代码来填充它:
您现在可以使用下拉列表来指定要连接的数据库到。当您获取数据时,请执行以下操作以获得正确的连接字符串:
Firstly add both connection settings to your app config file:
In your application add a ComboBox to the form and (called uiConnection in this example) and add the following code to populate it:
You can now use the drop down to specify which database to connect to. When you fetch your data do the following to get the correct connection string:
如果两者的数据相同,那么我认为最简单的方法是仅更改连接字符串并在选择其他选项时切换它。
例子:
数据源=“服务器\DBInstance”;初始目录=“数据库名称”;用户ID=“用户”;密码=“密码”;
If the data is the same on both then I think the easiest way is to just change the connection string and switch it when the other option is selected.
Example:
Data Source="Server\DBInstance";Initial Catalog="DatabaseName";User ID="user";Password="password";
采用 SqlConnection 的 DataAdapter 应该存在重载。您可以手动创建它,并在连接时将其传递到数据适配器以选择不同的连接。
如果您查看 dataset.designer.cs 并找到构造函数,您将看到这是默认构造函数在应用程序设置中执行的操作。
There should be an overload on the DataAdapter which takes an SqlConnection. You can create this manually and pass it into your data-adapter when you connect to choose different connections.
If you look into your dataset.designer.cs and find the constructor, you will see that this is what the default constructor is doing from your appsettings.