我在哪里放置连接代码 [英] where do i place the connection code

查看:83
本文介绍了我在哪里放置连接代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我阅读了有关访问数据库的初学者防护的文章,但无法将其放在我的Web表单上.我在哪里放置连接?是否在页面加载事件上.

解决方案

在结构合理的解决方案中,您至少应将表示,业务和数据访问分为不同的层.尽管可以在表示层的web.config中维护连接字符串,但可以在数据层中维护与数据库的连接.


您可以将连接字符串放置在web中. < configuration>
内任何位置的配置文件 喜欢:

 <  配置 > ; 
<   ................  > 
<   ................  > 
<  连接字符串 > 

<  添加    ="   MyAccessConnection" 连接字符串   Provider = Microsoft .Jet.OLEDB.4.0; Data Source = | DataDirectory | \ MyData.mdb" 提供商名称  ="    / > 

<  添加    ="   MySqlConnection" 连接字符串  数据源= MyServerName;初始目录= MyDatabase;用户ID = sa;密码= 123xyz" 提供商名称  ="    / > 

<  /connectionstrings  > 
<   ................  > 
<   ................  > 
<  /configuration  >  




在想要获取这些连接字符串值的位置,可以使用:
VB.Net

 ConfigurationManager.ConnectionStrings(" );
ConfigurationManager.ConnectionStrings(" ]); 



C#

 ConfigurationManager.ConnectionStrings [" ].ToString();
ConfigurationManager.ConnectionStrings [" ].ToString(); 


这些将从web.config文件返回相应的连接字符串值

I read the article on beginners guard on accessing the database, but i cant place it on my web form. Where do i place the connection?. Is it on page load event.

解决方案

In a properly architected solution you should separate your presentation, business and data access into different layers at least. The connection to your database can be maintained in the data layer, although the connection string can be maintained in the web.config at the presentation layer.


You can place your connection string in web.config file anywhere inside <configuration>
Like:

<configuration>
<................>
<................>
<connectionstrings>

<add name="MyAccessConnection" connectionstring="Provider=Microsoft.Jet.OLEDB.4.0; Data Source=|DataDirectory|\MyData.mdb" providername="System.Data.OleDb" />

<add name="MySqlConnection" connectionstring="Data Source=MyServerName; Initial Catalog=MyDatabase; User Id=sa; Password=123xyz" providername="System.Data.SqlClient" />

</connectionstrings>
<................>
<................>
</configuration>




And at the place where you want to get these connection string values, you can use:
VB.Net

ConfigurationManager.ConnectionStrings("MyAccessConnection");
ConfigurationManager.ConnectionStrings("MySqlConnection"]);



C#

ConfigurationManager.ConnectionStrings["MyAccessConnection"].ToString();
ConfigurationManager.ConnectionStrings["MySqlConnection"].ToString();


These will return corresponding connection string values from web.config file


这篇关于我在哪里放置连接代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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