如何在C Sharp项目中使用多个数据库 [英] How to use Multiple Database in a C Sharp project

查看:120
本文介绍了如何在C Sharp项目中使用多个数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在C Sharp项目中使用多个数据库。有人可以帮帮我吗?

How to use multiple database in a C Sharp Project. Can anyone help me, please?

推荐答案

为每个人设置不同的SqlConnection。

然后你可以独立访问它们。
Set up different SqlConnection to each.
You can then access them independently.


你好,



在你的app.config中,你可以定义几个连接字符串:

Hello,

In your app.config, you can define several connection strings :
<configuration>
  <connectionstrings>
    <add name="cs_local">
    connectionString="Data Source=(local);Initial Catalog=YourDB;Integrated Security=True"/>
    <add name="cs_remote">
    connectionString="Data Source=YourServer;Initial Catalog=YourDB;Integrated Security=True"/>
  </add></add></connectionstrings>
</configuration>



然后,在您的代码隐藏中,您可以这样做:


And then, in your code-behind, you can do that :

string cs_name = string.Empty;
if (your condition) 
    cs_name = "cs_local";
else
    cs_name = "cs_remote";
var connectionString = ConfigurationManager.ConnectionStrings[cs_name].ConnectionString;



别忘了在Using Directives中添加System.Configuration;)


Don't forget to add System.Configuration in your Using Directives ;)


当我们对具有不同数据库的多个表执行某些操作时,使用多个数据库是非常有用的选项。对于使用你必须制作一些存储过程,使用两个数据库表执行访问数据库,如



这里,我创建了两个数据库1.Database1 2.Databse2



1.数据库表1



包含字段的tblData是:id,name



2.Databse of Databse2



包含字段的tblDemo是:联系



现在,我将记录插入位于不同数据库的两个差异表中,并附带存储过程



数据库1中的存储过程:



创建程序InserData



@id int,

@name varchar(50),

@contact varchar(50)



as

开始



插入tblData值(@ id,@ name)



exec test.dbo.InsertData @contact



结束



首先创建存储过程Databse2里面的dure



创建程序InserData



@contact varchar(50)



as

开始

插入tblDemo值(@contact)

end





按照上面的例子,你可以使用多个数据库来存储多个表中的数据。
The use of multiple database is very gud option when we performing some operation on multiple tables with different databases. For using you have to make some stored procedure which performing with two database tables accessing the database as like

Here, I created two databse 1.Database1 2.Databse2

1.Tables of Database1

tblData containing with fields are: id,name

2.Tables of Databse2

tblDemo containing with field are: Contact

Now, I inserting record in two difference table located to different database with stored procedure

Stored Procedure in Database1:

Create procedure InserData
(
@id int,
@name varchar(50),
@contact varchar(50)
)
as
begin

Insert into tblData values(@id,@name)

exec test.dbo.InsertData @contact

end

First Create stored procedure inside of Databse2

Create procedure InserData
(
@contact varchar(50)
)
as
begin
Insert into tblDemo values(@contact)
end


As per, above example you can be able to work with multiple database to stored data in multiple tables.


这篇关于如何在C Sharp项目中使用多个数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆