2011年2月13日 星期日

使用傳統方式建立連線

   不透過Web.config的字串建立連線而是使用連線字串方式建立連線。

      //建立連線字串
        string connString = "Data Source=.\\sqlexpress;";
        connString += "Initial Catalog=lottery;";
        connString += "Persist Security Info=True;";
        connString += "User Id=xcsa;";
        connString += "Password=xcaa123;";
      //建立連線
        SqlConnection con = new SqlConnection(connString);
       //開啟連線
        con.Open();
        string SELSTR = "select * from Awards where 數量>=@數量";
        SqlCommand SELcmd = new SqlCommand(SELSTR, con);
      //設定查詢變數
        SELcmd.Parameters.Add("@數量", SqlDbType.NVarChar, 10).Value = "10";
       //查詢資料並將資料儲存於DATASET中
        SqlDataAdapter da = new SqlDataAdapter(SELcmd);
        DataSet ds = new DataSet();
        da.Fill(ds);
      //印出查詢內容
        if (ds.Tables[0].Rows.Count != 0)
        {
            Response.Write(ds.Tables[0].Rows[0]["品名"].ToString());
            Response.Write("<br>");
            Response.Write(ds.Tables[0].Rows[1]["備註"].ToString());
        }
       //資源回收
        SELcmd.Dispose();
        da.Dispose();
        ds.Dispose();

沒有留言:

張貼留言