且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

多个数据库连接

更新时间:2021-10-17 22:45:21

是的,您可以在单个应用程序中使用多个数据库。这可以通过更新连接字符串来实现,在同一服务器或不同的服务器中,您可以根据您的要求替换/添加数据库名称或服务器名称。



假设在您的配置文件中,您有一个连接字符串

Yes you can use multiple databases in a single application. This can be achieved by updating your connection string where in a same server or different server you can replace /add the database name or server name based on your requirement.

Suppose in your config file you have a connection string
<add name="DefectConnection">
			 connectionString="Data Source=SERVERNAME; Trusted_Connection=true;" providerName="System.Data.SqlClient"
				 /></add>





在运行时,您要添加数据库名称。因此,在代码中添加初始目录,如下所示:





At run time you want to add the database name. So add Initial Catalog within your code as below:

protected const string ConnectionStringKey = "DefaultConnection";
static string preConString = ConfigurationManager.ConnectionStrings[ConnectionStringKey].ConnectionString;
private static string conString = String.Format("{0};Initial Catalog={1}", preConString, "YOUR DATABASENAME");





您可以在此处使用配置设置获取连接名称,您可以使用要使用的数据库名称更改数据库名称。



您可以在代码中的任何地方使用它们。



您也可以使用多个连接字符串。



希望这会有所帮助。



Here you can use the configuration settings to get the connection name, you will be able to change the database name with the database name that you want to use.

You can use them within any place within your code.

Also you can use multiple connection strings as well.

Hope this will help.