ASP.NET 資料庫連線[搭配Web.config中的自訂字串(appSettings)]

  • 12278
  • 0
  • 2013-08-30

摘要:ASP.NET 資料庫連線[讀取Web.config中的自訂字串(appSettings)]

在寫ASP.NET時,最常使用到資料庫的存取,

所以此篇文章就分享基本的如何建立與資料庫的連線

首先,個人習慣在Web.config中設定資料庫的連線字串

所以我們先打開Web.config

在當中輸入


  <appSettings>
    <add key="conStr" value="Data Source=資料庫位置;Initial Catalog=資料庫名稱;User ID=帳號;Password=密碼"/>
  </appSettings>

之後就要進行我們的資料庫連線啦

step 1:引用命名空間


using System.Data.SqlClient;
using System.Configuration;

當中,SqlClient是我們接下來需要用到的資料庫命名空間,Configuration則是需要用來存取剛剛上述Web.config中的連線字串

step 2:開始進行連線啦~~


string connectStr;
string sql;
SqlConnection sqlCon;
SqlDataAdapter sqlAdp;
SqlCommand cmd;
DataSet ds;
DataView dv;

//透過ConfigurationManager來抓取我們剛剛在Web.config中設定的連線字串
connectStr=ConfigurationManager.AppSettings["conStr"];

//建立連結
sqlCon=new SqlConnection(connectStr);

//打開連結
sqlCon.Open();
sqlAdp=new SqlDataAdapter();
ds=new DataSet();

//基本的SQL 查詢語法
sql="select * from item";


//建立SQL命令對象,並將查詢語法和連結帶入
cmd=new SqlCommand(sql,sqlCon);
sqlAdp.SelectCommand = cmd;
sqlAdp.Fill(ds);

//取得結果Table,並將其給DataView
dv = new DataView(ds.Tables[0]);

//關閉連結,有開就有關
sqlCon.Close();

以上就是小弟今天分享的基本的資料庫連結

給有需要的同伴,在此下台一鞠躬