从web.config中源$ C ​​$ C文件使用的ConnectionString [英] Use connectionstring from web.config in source code file

查看:84
本文介绍了从web.config中源$ C ​​$ C文件使用的ConnectionString的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这可能是一个很基本的问题,但也许这就是为什么我在寻找答案的问题。现在我做这样的事情创造了我的源文件的数据库连接:

 的SqlConnection CON =新的SqlConnection(数据源= ...密码= ...);
CMD的SqlCommand =新的SqlCommand(的String.Format(SELECT * FROM表;),CON);
con.Open();
SqlDataReader的读者= cmd.ExecuteReader();

但是,这意味着,如果我选择更改数据库,这将是一个重大的痛苦。难道你们知道如何使用连接字符串从web.config文件呢?

感谢您!


解决方案

 的SqlConnection CON =新SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings[\"ConnectionStringNameFromWebConfig\"].ConnectionString);

请确保您的网站有System.Configuration的引用,否则将无法正常工作。

该文档可以发现如何:读取网络连接字符串。配置文件,用code样品

I know this might be a very basic question, but maybe thats why I'm having problems finding the answer. Right now I'm creating database connections in my source files by doing something like this:

SqlConnection con = new SqlConnection("Data Source=...Password=...);
SqlCommand cmd = new SqlCommand(String.Format("SELECT * FROM Table;"), con);
con.Open();
SqlDataReader reader = cmd.ExecuteReader();

But this means that if I choose to change databases it will be a major pain. Do you guys know how to use the connection string from a web.config file instead?

Thank you!

解决方案

SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionStringNameFromWebConfig"].ConnectionString);

Make sure that your website has a reference to System.Configuration or it won't work.

The documentation can be found as How to: Read Connection Strings from the Web.config File, with code sample

这篇关于从web.config中源$ C ​​$ C文件使用的ConnectionString的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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