asp.net連接數據庫方式

<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);"><span style="font-size:18px;">1.在web.config文件中配置連接字符串,在.cs文件中調用</span></span>

web.config 文件中:

<span style="font-size:18px;">   <connectionStrings>
    <add name="conn" connectionString="Data Source=(local);Initial Catalog=DatabasePractice ;User ID= sa ;Password=********"/>
  </connectionStrings></span>

.cs 文件中

<span style="font-size:18px;">string str = System.Configuration.ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
            SqlConnection sqlstr = new SqlConnection(str);
            sqlstr.Open();</span>

也可以用settings標記

<span style="font-size:18px;"><appSettings>
    <add key="conn" value="server=10.1.1.60;database=DatabasePractice;uid=sa;password=tangjue123;"/>
  </appSettings></span>
<span style="font-size:18px;">.cs文件:</span>
<span style="font-size:18px;">string str = System.Configuration.ConfigurationManager.AppSettings["conn"];
            SqlConnection sqlstr = new SqlConnection(str);
            sqlstr.Open();

</span>

appSettings 和 connectionStrings 的區別:

(1) appSettings 是在 2003 中常用的,connectionStrings 是在 2005 中常用的;

(2) 使用 connectionStrings 的好處:

第一,可將連接字符串加密,使用MS的一個加密工具即可;

第二,可直接綁定數據源控件,而不必寫代碼讀出來再賦值給控件;

第三,可方便的更換數據庫平臺,如換爲 Oracle 數據庫,只需要修改 providerName。

(3) 寫在 appSettings 中用 System.Configuration.ConfigurationManager.AppSettings["keyname"] 獲取數據庫連接代碼值;寫在 connectionStrings 中用 System.Configuration.ConfigurationManager.ConnectionStrings["name"] 獲取數據庫連接代碼值。

後面就是在後臺操作數據庫的過程了


2.直接在後臺連接數據庫

<span style="font-size:18px;">string str = "Data Source=(local);Initial Catalog=DatabasePractice ;User ID= sa ;Password=******* ";(本地數據庫)
string str1 = "Data Source=10.1.1.60;Initial Catalog=DatabasePractice ;User ID= sa ;Password=****** ";(網絡數據庫)
            SqlConnection conn = new SqlConnection(str1);
            conn.Open();</span></span>
後面就是是操作數據庫了。

關於數據庫連接語句的介紹,請查看:http://blog.csdn.net/tangjue18246068217/article/details/51276711


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章