iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 10
1
自我挑戰組

後端或是ASP.NET Core的學習筆記系列 第 10

第10天:超難用的ADO.NET(1)

我們上次建立的Product資料表。那這次我們就先用最古老的ADO.NET連線方式來去資料庫拿資料。

首先,MVC的分層架構告訴我們要做一個獨立的Model來處理資料連線。

所以我們來建立一個類別,並撰寫一個方法來拿取資料庫資料。

對Model資料夾按右鍵>加入>類別,然後輸入類別名稱後按確認。
https://ithelp.ithome.com.tw/upload/images/20200925/20120420FjR1bdQb2G.png

https://ithelp.ithome.com.tw/upload/images/20200925/20120420t4C0h1Lxyd.png

我這邊把類別取名為AdoNetDBModel,資料處理類別後面加上Model字樣是我的習慣,似乎很多人(?)也這麼做,就當作通則就好。

接下來我們需要一個連線字串,告訴ADO.NET我們要連到哪一個資料庫。

這個連接字串是有格式的,要指定資料庫伺服器路徑,並指定是伺服器中的哪一個資料庫,還要驗證連線方式等等。
最簡單的方式是從Visual Studio 的SQL Server物件總管,對資料庫右鍵>屬性,裡面拿到我們要使用的資料庫的連線字串。

Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=AspCoreIThelp2020;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False

https://ithelp.ithome.com.tw/upload/images/20200925/201204205csXZkRB8w.png
https://ithelp.ithome.com.tw/upload/images/20200925/20120420hwEpOFH3hx.png

這裡我的類別中宣告了,ConnetionString屬性來代表我的連線字串。

並在類別建構式中設定連線字串,另外要注意反斜線(\)在字串中是特殊功能字元,要用兩個反斜線(\),才能正常輸出一個反斜線
https://ithelp.ithome.com.tw/upload/images/20200925/20120420v9etJ6qDag.png

接下來我們要設定一個方法來取得資料庫資料,這邊我指定使用SQL Server專用的資料連線類別SqlConnection來與SQL server連線,這要額外的安裝套件。
https://ithelp.ithome.com.tw/upload/images/20200925/2012042023qQmuke9e.png

這個資料撰寫方法如下,剩下的部分明天再說~~

public List<Product> Get() {

            List<Product> result = new List<Product>();

            using (DbConnection connection = new SqlConnection(this.ConnetionString))
            {
                using (DbCommand command = connection.CreateCommand())
                {
                    command.CommandText = "Select Id, Name, Price From Product";
                    connection.Open();
                    DbDataReader reader = command.ExecuteReader();
                    while (reader.Read())
                    {
                        result.Add(new Product
                        {
                            Id = Convert.ToInt32(reader["Id"]),
                            Name = reader["Name"].ToString(),
                            Price = Convert.ToDecimal(reader["Price"])
                        });
                    }
                    connection.Close();
                }

            }
            return result;
        }

上一篇
第9天:ASP.NET Core與資料庫連線的幾種方法
下一篇
[影片]第11天:將Model資料傳給View-超難用的ADO.NET(2)
系列文
後端或是ASP.NET Core的學習筆記30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言